admin管理员组文章数量:1315989
Given a collection, how can I remove only the first item that matches a condition?
For example, given this collection:
[
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 3, name: "james" },
{ id: 4, name: "james" }
]
Filter out the first result that matches { name: "james" }
.
Result:
[
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 4, name: "james" }
]
Given a collection, how can I remove only the first item that matches a condition?
For example, given this collection:
[
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 3, name: "james" },
{ id: 4, name: "james" }
]
Filter out the first result that matches { name: "james" }
.
Result:
[
{ id: 1, name: "don" },
{ id: 2, name: "don" },
{ id: 4, name: "james" }
]
Share
Improve this question
edited Sep 18, 2017 at 2:03
Don P
asked Sep 18, 2017 at 1:42
Don PDon P
63.8k121 gold badges318 silver badges447 bronze badges
5
-
3
array.splice(array.findIndex(({ name }) => name === 'james'), 1)
withoutunderscore.js
at least. – Patrick Roberts Commented Sep 18, 2017 at 1:45 - Don't you mean findIndex? – jas7457 Commented Sep 18, 2017 at 1:47
- @jas7457 derp, thanks – Patrick Roberts Commented Sep 18, 2017 at 1:47
- @PatrickRoberts want to post as an answer? I'll accept it :) – Don P Commented Sep 18, 2017 at 2:07
- @DonP why? It's not a valid answer to your question. – Patrick Roberts Commented Sep 18, 2017 at 2:07
3 Answers
Reset to default 5Using underscore.js _.without
and _.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./ajax/libs/underscore.js/1.8.3/underscore-min.js"></script>
Using Lodash _.without
and _.find
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./ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
Are you are looking a solution like this?
Iterate and update an array using 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);
with Lodash
var newArray = _.without(array, _.find(array, { name: "james" }));
本文标签: javascriptRemove first matching item in a collectionStack Overflow
版权声明:本文标题:javascript - Remove first matching item in a collection - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741983101a2408515.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论