I am performing push operation to an array of objects. My code looks similar as shown below,
var obj = {"id":1, "fname":"john", "lname":"doe"};
var userArray = [{
"id": 1,
"fname": "john",
"lname": "doe"
}, {
"id": 2,
"fname": "john",
"lname": "doe"
}];
userArray.forEach(function (element) {
if(element.id !== obj.id) {
userArray.push(obj);
}
});
console.log(userArray);
when i do push operation on userArray which already contains an object which i am pushing (from code it is var obj = {"id":1, "fname":"john", "lname":"doe"};
) it pushes it to array on second pass in for loop.
Expected output should be userArray = [{"id": 1,"fname": "john","lname": "doe"}, {"id": 2, "fname": "john","lname": "doe"}];
but i am getting userArray = [{"id": 1,"fname": "john","lname": "doe"}, {"id": 2, "fname": "john","lname": "doe"}, {"id": 1,"fname": "john","lname": "doe"}];
How do i push only unique objects to array?
You need to search for an user with the same id, if it does not exist, then you can add it. You need to traverse the whole array first to check all the elements.
Use the array
.some
method to check if there is already an item in the list with that ID. If there isn't, then push into the array:I see two possible solutions:
1) Checking that the
id
does not exist.This code (or any improved loop-based version) iterates the array each time, that is why I prefer the second option.
2) Making
userArray
an object with theid
as index.