Artemis
Artemis

Reputation: 599

Remove objects from array based on their property with javascript

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

Upvotes: 0

Views: 52

Answers (6)

Emanuel Trandafir
Emanuel Trandafir

Reputation: 1653

you can apply a filter like so:

items = items.filter(el => el.rank != "0")

Upvotes: 1

StepUp
StepUp

Reputation: 38209

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

Upvotes: 1

Ilijanovic
Ilijanovic

Reputation: 14924

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

Upvotes: 1

Pavan
Pavan

Reputation: 1015

You can use Array.filter method to do that.

items = items.filter(i=> {
   return i.rank !== '0';
});

Upvotes: 1

Rajneesh
Rajneesh

Reputation: 5318

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

Upvotes: 1

Sudhanshu Bhagwat
Sudhanshu Bhagwat

Reputation: 392

You can just add a filter to the Items array :

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

Upvotes: 1

Related Questions