0

Given the array of objects:

var items = [
{"rank":"3","color":"red"},
{"rank":"4","color":"blue"},
{"rank":"0","color":"green"},
{"rank":"6","color":"blue"},
{"rank":"0","color":"yellow"}
];

I want to remove all the enries with rank 0, so that the result will be:

Items:

[{"rank":"3","color":"red"},
{"rank":"4","color":"blue"},
{"rank":"6","color":"blue"}];
Artemis
  • 589
  • 1
  • 6
  • 19

6 Answers6

1

You can just add a filter to the Items array :

items.filter(item => item.rank > 0)
1

Apply filter :

var items = [{"rank":"3","color":"red"},{"rank":"4","color":"blue"},{"rank":"0","color":"green"},{"rank":"6","color":"blue"},{"rank":"0","color":"yellow"}];

result = items.filter(({rank})=>rank>0);
console.log(result);
gorak
  • 5,233
  • 1
  • 7
  • 19
1

You can use Array.filter method to do that.

items = items.filter(i=> {
   return i.rank !== '0';
});
Pavan
  • 985
  • 2
  • 15
  • 27
1

var items = [
{"rank":"3","color":"red"},
{"rank":"4","color":"blue"},
{"rank":"0","color":"green"},
{"rank":"6","color":"blue"},
{"rank":"0","color":"yellow"}
];

let filteredArray = items.filter(el => el.rank > 0);

console.log(filteredArray);
bill.gates
  • 14,145
  • 3
  • 19
  • 47
1

Try to filter by trusy value and apply + sign to convert from string to number:

var items = [
   {"rank":"3","color":"red"},
   {"rank":"4","color":"blue"},
   {"rank":"0","color":"green"},
   {"rank":"6","color":"blue"},
   {"rank":"0","color":"yellow"}
];

result = items.filter(({rank})=> +rank);
console.log(result);
StepUp
  • 36,391
  • 15
  • 88
  • 148
  • @Artemis_ [The + operator returns the numeric representation of the object.](https://stackoverflow.com/questions/6682997/what-is-the-purpose-of-a-plus-symbol-before-a-variable) – StepUp May 18 '20 at 08:36
1

you can apply a filter like so:

items = items.filter(el => el.rank != "0")
Emanuel Trandafir
  • 1,526
  • 1
  • 5
  • 13