Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

remove item from array using its name / value

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

like image 890
G-Man Avatar asked Jun 10 '11 18:06

G-Man


People also ask

How do you remove an element from an array based on value?

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.

What is the most efficient way to remove an element from an array?

Most efficient way to remove an element from an array, then reduce the size of the array.


2 Answers

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'); 
like image 110
John Strickler Avatar answered Sep 29 '22 17:09

John Strickler


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'); 
like image 28
Rocket Hazmat Avatar answered Sep 29 '22 18:09

Rocket Hazmat