I have the following array
var countries = {};  countries.results = [     {id:'AF',name:'Afghanistan'},     {id:'AL',name:'Albania'},     {id:'DZ',name:'Algeria'} ];   How can I remove an item from this array using its name or id ?
Thank you
We can use the following JavaScript methods to remove an array element by its value. indexOf() – function is used to find array index number of given value. Return negavie number if the matching element not found. splice() function is used to delete a particular index value and return updated array.
Most efficient way to remove an element from an array, then reduce the size of the array.
Created a handy function for this..
function findAndRemove(array, property, value) {   array.forEach(function(result, index) {     if(result[property] === value) {       //Remove from array       array.splice(index, 1);     }       }); }  //Checks countries.result for an object with a property of 'id' whose value is 'AF' //Then removes it ;p findAndRemove(countries.results, 'id', 'AF'); 
                        Array.prototype.removeValue = function(name, value){    var array = $.map(this, function(v,i){       return v[name] === value ? null : v;    });    this.length = 0; //clear original array    this.push.apply(this, array); //push all elements except the one we want to delete }  countries.results.removeValue('name', 'Albania'); 
                        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