Reputation:
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
Upvotes: 1
Views: 3934
Reputation: 2598
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
Upvotes: 0
Reputation: 1013
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/
Upvotes: 0
Reputation: 11592
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);
Upvotes: 2