0

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

1
  • @why have you tagged it with recactjs?? its plain javascript Commented Nov 29, 2020 at 14:00

2 Answers 2

2

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);
Sign up to request clarification or add additional context in comments.

Comments

1
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.