ciokua ciokua
ciokua ciokua

Reputation: 45

Map specific array from largest to smallest reactjs

Hi guys I have array like this

const tmp = [{watch: 87}, {watch: 22}, {watch: 68},{watch: 24}, {watch: 35}]

The result what I want

87
68
35

So I want map array but only need 3 and sort from largest to smallest

Can someone help me how to filter like that ? thank you :D

Upvotes: 0

Views: 348

Answers (2)

Shihara Dilshan
Shihara Dilshan

Reputation: 303

const tmp = [{watch:87},{watch:22},{watch:68},{watch:24},{watch:35}]

const sortedArray = tmp.sort( (a,b) => { 
     if(a.watch > b.watch){
         return -1;
     }else{
         return 1;
     }
});

console.log(sortedArray);

The answer will be like this

[                                                                                                                                                                                                                                          
  { watch: 87 },                                                                                                                                                                                                                           
  { watch: 68 },                                                                                                                                                                                                                           
  { watch: 35 },                                                                                                                                                                                                                           
  { watch: 24 },                                                                                                                                                                                                                           
  { watch: 22 }                                                                                                                                                                                                                            
]  

The answer is an sorted array. So you can get your answer by

sortedArray.forEach(value -> console.log(value.watch))

You can use

slice(0,3)

to reduce the number of output to 3.

Upvotes: 1

GnanaJeyam
GnanaJeyam

Reputation: 3170

Here is the answer using sort, map and slice methods.

const tmp = [{watch:87},{watch:22},{watch:68},{watch:24},{watch:35}];

tmp.sort((a, b) => b.watch - a.watch).map(a => a.watch).slice(0,3);

Upvotes: 2

Related Questions