javascript 使用 UnderscoreJS 从数组中删除项目
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16994212/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Remove an item from array using UnderscoreJS
提问by climboid
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!
我想从数组中删除 id = 3 的项目。有没有不拼接的方法?Maye 使用下划线或类似的东西?
谢谢!
回答by Felix Kling
Just using plain JavaScript, this has been answered already: remove objects from array by object property.
只使用普通的 JavaScript,这已经得到了回答:通过对象属性从数组中删除对象。
Using underscore.js, you could combine .findWhere
with .without
:
使用underscore.js,你可以结合.findWhere
使用.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.
尽管如此,由于您在这种情况下无论如何要创建一个新数组,您可以简单地使用_.filter
or 本地Array.prototype.filter
函数(就像另一个问题中所示)。然后你只会迭代数组一次,而不是像这里那样可能迭代两次。
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.
如果要就地修改数组,则必须使用.splice
. 这也显示在另一个问题中,并且 undescore 似乎没有为此提供任何有用的功能。
回答by Sushanth --
You can use Underscore .filter
您可以使用下划线 .filter
var arr = [{
id: 1,
name: 'a'
}, {
id: 2,
name: 'b'
}, {
id: 3,
name: 'c'
}];
var filtered = _(arr).filter(function(item) {
return item.id !== 3
});
Can also be written as:
也可以写成:
var filtered = arr.filter(function(item) {
return item.id !== 3
});
var filtered = _.filter(arr, function(item) {
return item.id !== 3
});
You can also use .reject
你也可以使用 .reject
回答by greenafrican
回答by PeteGO
Underscore has a _without()method perfect for removing an item from an array, especially if you have the object to remove.
Underscore有一个_without()方法非常适合从数组中删除一个项目,特别是如果你有要删除的对象。
Returns a copy of the array with all instances of the values removed.
返回数组的副本,其中删除了所有值的实例。
_.without(["bob", "sam", "fred"], "sam");
=> ["bob", "fred"]
Works with more complex objects too.
也适用于更复杂的对象。
var bob = { Name: "Bob", Age: 35 };
var sam = { Name: "Sam", Age: 19 };
var fred = { Name: "Fred", Age: 50 };
var people = [bob, sam, fred]
_.without(people, sam);
=> [{ Name: "Bob", Age: 35 }, { Name: "Fred", Age: 50 }];
If you don't have the item to remove, just a property of it, you can use _.findWhere
and then _.without
.
如果您没有要删除的项目,只有它的一个属性,您可以使用_.findWhere
然后_.without
。
回答by Srihari Sridharan
Please exercise care if you are filtering strings and looking for case insensitive filters. _.without() is case sensitive. You can also use _.reject() as shown below.
如果您正在过滤字符串并寻找不区分大小写的过滤器,请小心。_.without() 区分大小写。您还可以使用 _.reject() ,如下所示。
var arr = ["test","test1","test2"];
var filtered = _.filter(arr, function(arrItem) {
return arrItem.toLowerCase() !== "TEST".toLowerCase();
});
console.log(filtered);
// ["test1", "test2"]
var filtered1 = _.without(arr,"TEST");
console.log(filtered1);
// ["test", "test1", "test2"]
var filtered2 = _.reject(arr, function(arrItem){
return arrItem.toLowerCase() === "TEST".toLowerCase();
});
console.log(filtered2);
// ["test1", "test2"]
回答by Sajjad Shirazy
Other answers create a new copy of the array, if you want to modify the array in place you can use:
其他答案创建数组的新副本,如果您想就地修改数组,您可以使用:
arr.splice(_.findIndex(arr, { id: 3 }), 1);
But that assumes that the element will always be found inside the array (because if is not found it will still remove the last element). To be safe you can use:
但这假设元素将始终在数组中找到(因为如果未找到它仍将删除最后一个元素)。为安全起见,您可以使用:
var index = _.findIndex(arr, { id: 3 });
if (index > -1) {
arr.splice(index, 1);
}
回答by BlackBeard
Use can use plain JavaScript's Array#filter
method like this:
使用可以像这样使用纯 JavaScript的Array#filter
方法:
var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
var filteredArr = arr.filter(obj => obj.id != 3);
console.log(filteredArr);
Or, use Array#reduce
and Array#concat
methods like this:
或者,使用Array#reduce
和Array#concat
方法如下:
var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
var reducedArr = arr.reduce((accumulator, currObj) => {
return (currObj.id != 3) ? accumulator.concat(currObj) : accumulator;
}, []);
console.log(reducedArr);
NOTE:
笔记:
- Both of these are pure functional approach (i.e.they don't modify the existing array).
- No, external library is required in these approach (Vanilla JavaScript is enough).
- 这两种方法都是纯函数式方法(即它们不修改现有数组)。
- 不,这些方法需要外部库(Vanilla JavaScript 就足够了)。
回答by Nadeem
or another handy way:
或其他方便的方式:
_.omit(arr, _.findWhere(arr, {id: 3}));
my 2 cents
我的 2 美分
回答by Anand Tamizh
By Using underscore.js
通过使用 underscore.js
var arr = [{id:1,name:'a'},{id:2,name:'b'},{id:3,name:'c'}];
var resultArr = _.reject(arr,{id:3});
console.log(resultArr);
The result will be :: [{id:1name:'a'},{id:2,name:'c'}]
结果将是 :: [{id:1name:'a'},{id:2,name:'c'}]
回答by Bastin Robin
I used to try this method
我曾经尝试过这个方法
_.filter(data, function(d) { return d.name != 'a' });
There might be better methods too like the above solutions provided by users
可能还有更好的方法,比如用户提供的上述解决方案