user8006446
user8006446

Reputation: 475

Placing an item at the front of a mapped array

I'd like to map through some data and render a component for each item. An example of the data is as follows:

[{
name: 'Ipad',
price: 500,
},
{name: 'IWatch',
price: 400,
new: true,
},
{name: 'Ipad',
price: 300,
}]

How could I do this so that the item which has the value of new: true appears at the beginning of the array and therefore at the top of the page/list when it is rendered?

I'm using React, so if I was to do a standard map through, it would look something like this:

{items.map((item, index) => (<Component key={index} item={item} />)} 

Upvotes: 0

Views: 91

Answers (1)

Lanil Marasinghe
Lanil Marasinghe

Reputation: 2915

{items.sort((a,b) => a.new ? -1 : 1).map((item, index) => (<Component key={index} item={item} />)} 

Upvotes: 3

Related Questions