Thursday, April 25, 2024
91
rated 0 times [  97] [ 6]  / answers: 1 / hits: 188143  / 11 Years ago, fri, june 7, 2013, 12:00:00

Say I have this code




var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];


and I want to remove the item with id = 3 from the array. Is there a way of doing this without splicing? Maye something using underscore or something like that?

Thanks!


More From » underscore.js

 Answers
20

Just using plain JavaScript, this has been answered already: remove objects from array by object property.



Using underscore.js, you could combine .findWhere with .without:





var arr = [{
id: 1,
name: 'a'
}, {
id: 2,
name: 'b'
}, {
id: 3,
name: 'c'
}];

//substract third
arr = _.without(arr, _.findWhere(arr, {
id: 3
}));
console.log(arr);

<script src=https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js></script>





Although, since you are creating a new array in this case anyway, you could simply use _.filter or the native Array.prototype.filter function (just like shown in the other question). Then you would only iterate over array once instead of potentially twice like here.



If you want to modify the array in-place, you have to use .splice. This is also shown in the other question and undescore doesn't seem to provide any useful function for that.


[#77746] Thursday, June 6, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
rhett

Total Points: 671
Total Questions: 100
Total Answers: 102

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
rhett questions
Thu, Oct 28, 21, 00:00, 3 Years ago
Mon, Aug 2, 21, 00:00, 3 Years ago
Fri, Dec 11, 20, 00:00, 3 Years ago
Fri, Aug 7, 20, 00:00, 4 Years ago
Thu, Mar 26, 20, 00:00, 4 Years ago
;