How can I remove an object from an array?
I wish to remove the object that includes name Kristian
from someArray
. For example:
som
This answer
for (var i =0; i < someArray.length; i++)
if (someArray[i].name === "Kristian") {
someArray.splice(i,1);
}
is not working for multiple records fulfilling the condition. If you have two such consecutive records, only the first one is removed, and the other one skipped. You have to use:
for (var i = someArray.length - 1; i>= 0; i--)
...
instead .
Use javascript's splice() function.
This may help: http://www.w3schools.com/jsref/jsref_splice.asp
How about this?
$.each(someArray, function(i){
if(someArray[i].name === 'Kristian') {
someArray.splice(i,1);
return false;
}
});
The clean solution would be to use Array.filter:
var filtered = someArray.filter(function(el) { return el.Name != "Kristian"; });
The problem with this is that it does not work on IE < 9. However, you can include code from a Javascript library (e.g. underscore.js) that implements this for any browser.
someArray = jQuery.grep(someArray , function (value) {
return value.name != 'Kristian';
});
You can use map function also.
someArray = [{name:"Kristian", lines:"2,5,10"},{name:"John",lines:"1,19,26,96"}];
newArray=[];
someArray.map(function(obj, index){
if(obj.name !== "Kristian"){
newArray.push(obj);
}
});
someArray = newArray;
console.log(someArray);