2

I have an Array I want to remove duplicate object example bison is coming 2 times.

var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];

This is what I tried

let a =  beasts.indexOf(bison);
console.log(a);

But all the time it give -1 that means the object is not there at all

please ignore the values of the object

nitish
  • 111
  • 2
  • 13

4 Answers4

1

Use Array.filter and Set

Maintain a set of unique keys and if the value exists in the set, return false else add it to set and return true.

var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
let set = new Set();
let result = beasts.filter(o => {
  // Get the key of object 
  let key = Object.keys(o)[0];
  if(!set.has(key)) { // check for existence in set
    // if does not exist add it to set and return true (filter IN)
    set.add(key);
    return true;
  }
});
console.log(result);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

In a simple way

const beasts = ['John', 'Paul', 'George', 'Ringo', 'John'];

let beasts = [...new Set(names)];
console.log(unique); // 'John', 'Paul', 'George', 'Ringo'
Mr.M
  • 1,472
  • 3
  • 29
  • 76
0

To do this programmatically, maintain a separate array that will hold names of processed beasts and then reduce the original array in relation to processedBeastsArray;

var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];

const processedBeasts = [];
const result = beasts.reduce(function(final, current) {
  const currentBeastName = Object.keys(current)[0];
  if(!processedBeasts.includes(currentBeastName)){
    processedBeasts.push(currentBeastName);
    final.push(current);
  }
  return final;
}, []);
AdityaParab
  • 7,024
  • 3
  • 27
  • 40
0

You can also use a simple forEach() loop that has O(n) complexity to get that output.

var beasts = [ {'ant':false}, {'bison':true}, {'camel':true}, {'duck':false}, {'bison':false} ];
var resObj = {};
beasts.forEach((beast)=>{
  var key = Object.keys(beast)[0];
  if(!resObj[key]){
    resObj[key] = beast;
  }
});
var finalArrayRes = Object.values(resObj);
console.log(finalArrayRes);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62