I created an array like:
myarr: [
{ name:'London', population:'7000000' },
{ name:'Munich', population:'1000000' }
]
At some point I need to add some new elements to the array, but first I need to check if element with the same name already exists. If yes, the value must be updated. If no, the new element must be created and added. If the value in new element equals zero and the element exists, it must be removed from the array.
You can do like this
function myFunction(myarr, item) {
var found = false;
var i = 0;
while (i < myarr.length) {
if (myarr[i].name === item.name) {
// Do the logic (delete or replace)
found = true;
break;
}
i++;
}
// Add the item
if (!found)
myarr.push(item);
return myarr;
}
This should do the trick http://jsfiddle.net/tcwqV/
var arr = [
{ name:'London', population:'7000000' },
{ name:'Munich', population:'1000000' }
]
var addNewElement = function(arr, newElement) {
var found = false;
for(var i=0; element=arr[i]; i++) {
if(element.name == newElement.name) {
found = true;
if(newElement.population === 0) {
arr[i] = false;
} else {
arr[i] = newElement;
}
}
}
if(found === false) {
arr.push(newElement);
}
// removing elements
var newArr = [];
for(var i=0; element=arr[i]; i++) {
if(element !== false) newArr.push(element);
}
return newArr;
}
arr = addNewElement(arr, {name: 'Paris', population: '30000000'});
console.log(arr);
arr = addNewElement(arr, {name: 'Paris', population: '60000000'});
console.log(arr);
arr = addNewElement(arr, {name: 'Paris', population: 0});
console.log(arr);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With