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" }));