Remove array element based on object property
Solution 1
One possibility:
myArray = myArray.filter(function( obj ) {
return obj.field !== 'money';
});
Please note that filter
creates a new array. Any other variables referring to the original array would not get the filtered data although you update your original variable myArray
with the new reference. Use with caution.
Solution 2
Iterate through the array, and splice
out the ones you don't want. For easier use, iterate backwards so you don't have to take into account the live nature of the array:
for (var i = myArray.length - 1; i >= 0; --i) {
if (myArray[i].field == "money") {
myArray.splice(i,1);
}
}
Solution 3
Say you want to remove the second object by it's field property.
With ES6 it's as easy as this.
myArray.splice(myArray.findIndex(item => item.field === "cStatus"), 1)
Solution 4
In ES6, just one line.
const arr = arr.filter(item => item.key !== "some value");
:)
Solution 5
You can use lodash's findIndex to get the index of the specific element and then splice using it.
myArray.splice(_.findIndex(myArray, function(item) {
return item.value === 'money';
}), 1);
Update
You can also use ES6's findIndex()
The findIndex() method returns the index of the first element in the array that satisfies the provided testing function. Otherwise -1 is returned.
const itemToRemoveIndex = myArray.findIndex(function(item) {
return item.field === 'money';
});
// proceed to remove an item only if it exists.
if(itemToRemoveIndex !== -1){
myArray.splice(itemToRemoveIndex, 1);
}
Comments
-
imperium2335 almost 2 years
I have an array of objects like so:
var myArray = [ {field: 'id', operator: 'eq', value: id}, {field: 'cStatus', operator: 'eq', value: cStatus}, {field: 'money', operator: 'eq', value: money} ];
How do I remove a specific one based on its property?
e.g. How would I remove the array object with 'money' as the field property?
-
imperium2335 about 11 yearsWhy wouldn't I be able to rely on filter()?
-
Rob M. about 11 yearsBecause it is part of JavaScript 1.6, which isn't supported by IE8 and below or older browsers.
-
jessegavin about 11 yearsNote that
filter()
is only available for Internet Explorer 9+ -
jAndy about 11 years@jessegavin indeed. I should have mentioned that there are plenty of good es5 shim libraries available, which mimic the functionality (just in case you want to support legacy browsers)
-
Brian Glick over 9 years
filter()
creates a new array, which is fine if you're able to reassign the variable and know that there aren't other areas of code that have references to it. This won't work if you specifically need to modify the original array object. -
sisimh almost 9 yearswhat do you mean by the live nature of the array ? @Neit the Dark Absol
-
Klors almost 9 years@sisimh he means that if you iterate forwards over an array by using its length as part of the iteration logic and its length changes because it has elements removed or added you can end up running off the end of the array or not doing the operation for every item in the array. Going backwards makes that much less likely as it works towards a static 0 index rather than a moving length.
-
Chris Schaller almost 8 yearsThis is a very dangerous example to leave on the web... it works with the example data, but not with anything else. splice(i) means that it will remove all elements in the array starting at and after the first instance where value is money, which down not satisfy the requirement from op at all. If we changed to splice(i,1) it would still be incorrect because it would not evaluate the next sequential item (you would have to decrement i as well) This is why you should process remove operations in arrays backwards, so that removing an item doesn't alter the indexes of the next items to process
-
forgottofly over 7 yearsWhat is the array is a tree structure?
-
forgottofly over 7 yearsWhat if the array is a tree structure ar beforeDeleteOperationArray=[ { "id": 3.1, "name": "test 3.1", "activityDetails": [ { "id": 22, "name": "test 3.1" }, { "id": 23, "name": "changed test 23" } ] } ] and I want to delete id:23
-
forgottofly over 7 yearsWhat if the array is a tree structure ar beforeDeleteOperationArray=[ { "id": 3.1, "name": "test 3.1", "activityDetails": [ { "id": 22, "name": "test 3.1" }, { "id": 23, "name": "changed test 23" } ] } ] and I want to delete id:23
-
Sridhar over 7 years@forgottofly tree structure? I think
myArray
here is an array of objects. -
forgottofly over 7 yearsWhat if the array is a tree structure var beforeDeleteOperationArray=[ { "id": 3.1, "name": "test 3.1", "activityDetails": [ { "id": 22, "name": "test 3.1" }, { "id": 23, "name": "changed test 23" } ] } ] and I want to delete id:23
-
Patrick Borkowicz about 7 yearsKinda obvious but if you are only expecting to remove a single unique element, you can throw a break into the 'if' statement for performance so the loop doesn't needlessly iterate over the rest of the array.
-
kittu almost 7 years@Klors Thanks for explaining. Is it good to always read the array backwards as in the answer?
-
Niet the Dark Absol almost 7 years@Satyadev It's required here because
splice
changes the array. -
Niet the Dark Absol almost 7 years@Satyadev If iterating backwards is what you need, then go ahead and do it. If not, don't bother.
-
kittu almost 7 years@NiettheDarkAbsol Actually reading array in backwards is faster. Just figured it out from this link: stackoverflow.com/questions/8689573/…
-
Niet the Dark Absol almost 7 years@Satyadev Read the accepted answer on that question.
-
JackTheKnife almost 6 years@forgottofly good point - answer works only for limited cases. Did you found answer to your question?
-
forgottofly almost 6 yearsNo @JackTheKnife
-
Compaq LE2202x almost 6 yearsI tried this but instead of "removing" 3rd item from OP's array, your code "filtered" and displayed the 3rd item only.
-
David Mulder about 4 years@CompaqLE2202x 2 years later it's probably already obvious to you, but for future developers:
splice
changes the original array, so the value you get back is the item that was removed, but if you next look atmyArray
the item will be missing. -
gabrielstuff over 3 yearsThe Mozilla doc is pretty clear on it.
filter
is the best option you have : developer.mozilla.org/fr/docs/Web/JavaScript/Reference/… You can check support at the bottom of the page. It is all green for Chrome, FireFox, Edge, IE9+, Opera, Safari. On mobile, all major browsers support it. You are not in 2010, please keep code clean and stick to browsers standards. -
Yannic over 3 yearsIf the element is not found by findIndex (ES6 version), -1 is returned and the last element is removed by splice although it doesn't match the predicate.
-
Yannic over 3 yearsIf the element is not found by findIndex, -1 is returned and the last element is removed by splice although it doesn't match the predicate.
-
Sridhar over 3 years@Yannic Nice catch. Thanks for pointing it out. Updated my answer for it.
-
undefined almost 3 yearsSince the filter method will loop through the array, is it safe to assume that this will work fine with thousands of entries? My particular case is that I store websockets connections (each client has at least one, making them quite a lot) in an array on my server and upon disconnection need to remove the entry.
-
undefined almost 3 yearsCould probably also use ternary for that to keep it as a single line and avoid additional variable creation
-
Kurt Van den Branden over 2 yearsKeep in mind that filter creates a new array.