Thursday, July 26, 2018

Remove duplicates from an array in javascript.

1.)
let a=[7,2,3,2,3,1,2,4,8,5,6,9,5];
let  b=[];
for(let i=0;i<a.length;i++){
    if(b.indexOf(a[i])===-1){
        b.push(a[i]);
    }
}
console.log(b);//[ 7, 2, 3, 1, 4, 8, 5, 6, 9 ]

2.)
let a=[7,2,3,2,3,1,2,4,8,5,6,9,5];
a.sort();
let  b=[];
let _temp;
for(let i=0;i<a.length;i++){
    if(a[i] !== _temp){
        _temp=a[i];
        b.push(a[i]);
    }
}
console.log(b);//[ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]

3.)
let a=[7,2,3,2,3,1,2,4,8,5,6,9,5];
var obj={};
for(let i of a){
    obj[i]=true;
}
console.log(Object.keys(obj));

4.)
let a=[7,2,3,2,3,1,2,4,8,5,6,9,5];
console.log([... new Set(a)]);
let bSet=new Set(a);
console.log(bSet);

No comments:

Post a Comment

Find the value from array when age is more than 30

 const data = [   { id: 1, name: 'Alice', age: 25 },   { id: 2, name: 'Bob', age: 30 },   { id: 3, name: 'Charlie', ...