0

I have an array of objects with object properties "vote_average" and "file_path", I'm trying to find three objects that have the highest "vote_average" value, I still need the "file_path" property

I can find the single highest object using the code below, however I'm trying to find the 1st, 2nd and 3rd objects with the highest property value of "vote_average"

var fullFilmImages = data.images.backdrops;

var highestRatedImage = Math.max.apply(Math,fullFilmImages.map(function(img){
    return img.vote_average;}
))

var highestRatedImageOBJ = fullFilmImages.find(function(img){
    return img.vote_average == highestRatedImage; }
)

alert(JSON.stringify(highestRatedImageOBJ));

I have tried the .map method however I need the objects and not just the property value because the objects also contain another a property called "file_path" that I need

let filmImageRatings = fullFilmImages.map(allFilmImages => 
allFilmImages.vote_average).slice(0,3);
TF120
  • 297
  • 1
  • 3
  • 14

1 Answers1

2

Sort the array in descending order by the "vote_average" property and then take a slice of the array.

const objList = [{
    vote_average: 1221,
    file_path: 'dsf'
  },
  {
    vote_average: 100,
    file_path: 'asdf'
  },
  {
    vote_average: 32,
    file_path: 'hgk'
  },
    {
    vote_average: 1,
    file_path: 'hgk'
  }
]

console.log(objList)

objList.sort(function(a, b) {
  return b.vote_average - a.vote_average
})

console.log(objList.slice(0,3))
Jibin Joseph
  • 1,265
  • 7
  • 13