简体   繁体   中英

Delete element with a specific value from an array

I use vue.js and I want to delete elements of an array that have specific id value.

For example :

I want to delete elements that have id of 0. I tried to use the findindex and then delete the element but I couldn't implement that, and to use the splice method you have to know the index before deleting.

"Options": [
{
  "id": 0,
  "option": "A",
  "value": "2"
},
{
  "id": 0,
  "option": "B",
  "value": "1"
},
{
  "id": 0,
  "option": "C",
  "value": "3"
},
{
  "id": 1,
  "option": "A",
  "value": "1"
}

One more ( polyfill ):

 var array = [{id:1},{id:0},{id:0},{id:2}]; array = array.filter(x => x.id != 0); console.log(array); 

x => x.id != 0 is the same as function (x) { return x.id != 0; } function (x) { return x.id != 0; } .

for + splice (there are plenty of solutions with the same result):

 var array = [{id:1},{id:0},{id:0},{id:2}]; removeIf(array, x => x.id == 0); console.log(array); function removeIf (array, predicate) { var i, n = array.length; for (i = 0; i < n; i++) { if (predicate(array[i])) { array.splice((n--, i--), 1); } } } 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM