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?
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:
var obj = {"id":1, "fname":"john", "lname":"doe"};
var userArray = [{
"id": 1,
"fname": "john",
"lname": "doe"
}, {
"id": 2,
"fname": "john",
"lname": "doe"
}];
var existing = userArray.some(element => element.id === obj.id);
if(!existing) {
userArray.push(obj);
}
console.log(userArray);
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.
var obj = {"id":3, "fname":"john", "lname":"doe"};
var userArray = [{
"id": 1,
"fname": "john",
"lname": "doe"
}, {
"id": 2,
"fname": "john",
"lname": "doe"
}];
/*Search for an user with the same id*/
var found = userArray.find(function(user) {
return user.id == obj.id;
});
/*Add the user if not found*/
if(!found){
userArray.push(obj);
}
I see two possible solutions:
1) Checking that the id
does not exist.
var exists = false;
userArray.forEach(function (element) { // n/2 checks on average
if(element.id == obj.id) { // (this specific awful code, always n checks)
exists = true;
}
});
if (!exists) {
userArray.push(obj);
}
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 the id
as index.
var obj = {"id":1, "fname":"john", "lname":"doe"};
var userArray = {
1: {
"id": 1,
"fname": "john",
"lname": "doe"
},
2: {
"id": 2,
"fname": "john",
"lname": "doe"
}
};
if (typeof userArray[obj.id] === 'undefined') { // always 1 check
userArray[obj.id] = obj;
}
console.log(userArray);