Skip to content Skip to sidebar Skip to footer

Deduplicate Array Of Objects By Given Property Name

I have an array of objects with about 1500 elements, I am trying to make a new array removing the elements that have a duplicate unique property. But for some reason when I run the

Solution 1:

Create an object that uses the Numbers property as the keys. Since object keys must be unique, this will remove duplicates. Then get the object values to convert back to an array.

const DATA = [{ Numbers: 1 },{ Numbers: 2 },{ Numbers: 3 },{ Numbers: 4 },{ Numbers: 1 },{ Numbers: 4 }];
const result = Object.values(Object.fromEntries(DATA.map(a => [a.Numbers, a])));
console.log(result)

Solution 2:

You're really complicating matters. You're mapping twice, converting the result into a set, and then creating a new array from that set.

It would be much simpler (and more readable) to use a simple loop, and keep a record of the numbers in the objects. If a number already exists splice the object from the array.

This method won't create a new array - you're modifying the existing one - but it will work.

const arr = [{ number: 1 },{ number: 2 },{ number: 3 },{ number: 4 },{ number: 1 },{ number: 4 }];

const numbers = new Set();

for (let i = arr.length - 1; i >= 0 ; i--) {
  const { number } = arr[i];
  if (numbers.has(number)) arr.splice(i, 1);
  numbers.add(number);
}

console.log(arr);

Solution 3:

Since no Map-based answers yet (and I believe, Map suits the purpose the best from performance standpoint), I'll post mine:

const src = [{key: 'a', value: 1}, {key: 'c', value: 3}, {key: 'b', value: 2}, {key: 'a', value: 1}, {key: 'c', value: 3}]

const dedupe = (arr, keyProp) => [
    ...arr
        .reduce((acc, obj) => 
            (acc.set(obj[keyProp], obj), acc), new Map)
        .values()
]

const result = dedupe(src, 'key')

console.log(result)
.as-console-wrapper{min-height:100%;}

Solution 4:

The idiom for making an array of distinct objects (also described in this answer) goes like this:

const distinct = DATA.filter((obj, idx) => 
  idx === data.findIndex(a => a.Numbers === obj.Numbers));

This filters the input array by selecting all items that, when linearly searched for, return the same index they already have. Thus selecting the first of each such object with the given criteria.

Note: that some of your Numbers were strings and some were actual numbers. (Those with a leading 0 were stored as strings, like '02'.) You could use the less strict == instead of === if you need to deal with situations where the same value may be stored in both string and number format. e.g.: a.Numbers == obj.Numbers.


Post a Comment for "Deduplicate Array Of Objects By Given Property Name"