How to remove duplicates from an array in JavaScript

6 Answers

0 votes
function unique(arr) {
    arr = arr.concat().sort();
    for (let i = 1; i < arr.length; ) {
        if (arr[i - 1] === arr[i])
            arr.splice(i, 1);
        else
            i++;
    }
    return arr;
}
  
let arr = [5, 6, 3, 1, 1, 5, 5, 1, 7];
 
arr = unique(arr);
 
for (let i = 0; i < arr.length; i++) 
    console.log(arr[i]);
 
 
 
 
/*
run:
 
1
3
5
6
7
 
*/

 



answered Sep 23, 2020 by avibootz
edited Sep 23, 2020 by avibootz
0 votes
let arr = ["php", "javascript", "php", "css", "php", "javascript", "javascript"];
 
arr = Array.from(new Set(arr));
 
console.log(arr); 
 
 
 
 
/*
run:
 
["php", "javascript", "css"]
 
*/

 



answered Feb 14, 2021 by avibootz
edited Dec 13, 2021 by avibootz
0 votes
let arr = ["php", "javascript", "php", "css", "php", "javascript", "javascript"];
 
arr = [...new Set(arr)];
 
console.log(arr); 
 
 
 
 
/*
run:
 
["php", "javascript", "css"]
 
*/

 



answered Feb 14, 2021 by avibootz
edited Dec 13, 2021 by avibootz
0 votes
let arr = [5, 6, 3, 1, 1, 5, 5, 1, 7, 7, 7, 3];
  
arr = arr.filter((item,index) => arr.indexOf(item) === index)
  
for (let i = 0; i < arr.length; i++) 
    console.log(arr[i]);
  
  
  
  
/*
run:
  
5
6
3
1
7
  
*/

 



answered Dec 13, 2021 by avibootz
0 votes
const arr = ['x', 1, 'y', 1, '3', 'x', '1'];
  
const uarr = arr.filter(function(value, index, self) { 
  return self.indexOf(value) === index;
});
 
console.log(uarr);


/*
run:
   
[ 'x', 1, 'y', '3', '1' ]
   
*/
 

 



answered Sep 29 by avibootz
0 votes
let arr = ['x', 1, 'y', 1, '3', 'x', '1', 1, 1];
  
arr = arr.filter(function(value, index, self) { 
  return self.indexOf(value) === index;
});
 
console.log(arr);


/*
run:
   
[ 'x', 1, 'y', '3', '1' ]
   
*/
 

 



answered Sep 29 by avibootz
...