javascript - Add or update an array element -


i created array like:

myarr: [      { name:'london', population:'7000000' },     { name:'munich', population:'1000000' } ] 

at point need add new elements array, first need check if element same name exists. if yes, value must updated. if no, new element must created , added. if value in new element equals 0 , element exists, must removed array.

this should 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); 

Comments

Popular posts from this blog

html - How to style widget with post count different than without post count -

How to remove text and logo OR add Overflow on Android ActionBar using AppCompat on API 8? -

javascript - storing input from prompt in array and displaying the array -