-2

I simply want to get 3 highest price value objects as new array. How would I do that easily ?

For example i got array like this ..

const data = 
  [ { name: 'x', color: 'red',    price: 15 } 
  , { name: 'y', color: 'black',  price:  5 } 
  , { name: 'z', color: 'yellow', price: 25 } 
  , { name: 't', color: 'blue',   price: 10 } 
  , { name: 'n', color: 'blue',   price: 60 } 
  ] 
fatihcan8
  • 49
  • 5
  • Does this answer your question? [find the 3 largest values of an object array in javascript](https://stackoverflow.com/questions/46303248/find-the-3-largest-values-of-an-object-array-in-javascript) – pilchard Sep 11 '21 at 00:23

1 Answers1

0

You can sort the array by the price property (with Array.sort) and get the first three items (with Array.slice):

const arr=[{name:"x",color:"red",price:15},{name:"y",color:"black",price:5},{name:"z",color:"yellow",price:25},{name:"t",color:"blue",price:10},{name:"n",color:"blue",price:60}];

const result = arr.sort((a,b) => b.price - a.price).slice(0, 3)

console.log(result)
Spectric
  • 30,714
  • 6
  • 20
  • 43