鉴于一个集合,如何删除仅与条件匹配的第一个项目?
例如,给定此集合:
[
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 3, name: "james" },
{ id: 4, name: "james" }
]
过滤掉与{ name: "james" }
匹配的第一个结果。
结果:
[
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 4, name: "james" }
]
答案 0 :(得分:3)
您正在寻找这样的解决方案吗?
使用Array.prototype.splice
迭代并更新数组。
var arr = [
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 3, name: "james" },
{ id: 4, name: "james" }
];
// loop and remove the first match from the above array
for (i = 0; i < arr.length; i++) {
if (arr[i].name == "james"){
arr.splice(i, 1);
break;
}
}
// write into the browser console
console.log(arr);
&#13;
答案 1 :(得分:2)
使用underscore.js,您可以使用 _.without
和 findwhere
var myarray = [
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 3, name: "james" },
{ id: 4, name: "james" }
];
var arr = _.without(myarray, _.findWhere(myarray, {
name: "james"
}));
console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
使用Loadash ,
var myarray = [
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 3, name: "james" },
{ id: 4, name: "james" }
];
var result =_.without(myarray, _.find(myarray, { name: "james" }));
console.log(result);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
答案 2 :(得分:1)
与Lodash
var newArray = _.without(array, _.find(array, { name: "james" }));