'Push unique objects into array in JAVASCRIPT

I want to push object that only have unique id1 into array.

Example:

let array = [],
    obj = {},
    access = true

if(access){
   obj['id1'] = 1
   obj['id2'] = 2
   if(array.indexOf(obj.id1) == -1){
       array.push(obj)
   }
}

console.log(array);

In the above example I am trying to add value to obj then push the obj into array. But obj.id1 need to be unique. The method I am using above doesn't work in my case.

Thank you



Solution 1:[1]

As Taplar says, indexOf will look for the first instance of the thing you pass in in the other array. This won't work because there are no instances of the ids in the array, directly anyway.

Use the find function, which allow you pass in a comparison function, so you can define what a match is.

let initial = [{id:1}, {id:2}, {id:1}];
let result = initial.reduce((acc, item) => 
{
  if(!acc.find(other => item.id == other.id))
  {
    acc.push(item);
  }
  
  return acc;
}, []);

console.log(result);

Solution 2:[2]

Simplest solution . Lets say myObjArray have duplicate object use below es6 code to get unique array from that

// Creates an array of objects with unique "name" property values.

let uniqueObjArray = [ ...new Map(myObjArray.map((item) => [item["name"], item])).values(), ]; console.log("uniqueObjArray", uniqueObjArray);

Refer here for more detail https://yagisanatode.com/2021/07/03/get-a-unique-list-of-objects-in-an-array-of-object-in-javascript/

Solution 3:[3]

I think you need to use findIndex and not indexOf. Try replacing your if condition with the following:

    array.findIndex((o)=>{ return o.id1  === obj.id1 }) === -1

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Matt Ellen
Solution 2 kartick shaw
Solution 3 Cold Cerberus