Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove first matching item in a collection

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" }
]
like image 880
Don P Avatar asked Dec 31 '25 15:12

Don P


2 Answers

Using 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.com/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.com/ajax/libs/lodash.js/4.17.15/lodash.min.js"></script>
like image 127
Sajeetharan Avatar answered Jan 03 '26 04:01

Sajeetharan


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);
like image 31
Quinn Avatar answered Jan 03 '26 03:01

Quinn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!