Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add or update an array element [closed]

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.

like image 611
Kotanet Avatar asked Mar 22 '23 13:03

Kotanet


2 Answers

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;
}
like image 107
Adriien M Avatar answered Mar 25 '23 03:03

Adriien M


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);
like image 44
Krasimir Avatar answered Mar 25 '23 03:03

Krasimir