1

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

2
  • 2
    Take a look at the find method for arrays. The issue is that you are trying to match by a nested property, not the actual element in the array Commented May 12, 2020 at 13:56
  • Yes @Taplar that's the issue. Commented May 12, 2020 at 14:02

3 Answers 3

2

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);

Sign up to request clarification or add additional context in comments.

Comments

0

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/

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.