Getting max value(s) in JSON array

前端 未结 11 1717
醉梦人生
醉梦人生 2020-12-06 05:56

I\'m trying to create a JavaScript function which takes information from an array in an external JSON and then takes the max value (or the top 5 values) for one of the JSON

11条回答
  •  情书的邮戳
    2020-12-06 06:38

    My solution here. Remember to use == instead of === to compare a number with a string.

    const getMax = (arr, prop) => {
      const tmp = arr.map(x => x[prop]);
      const max = Math.max(...tmp);
      return arr.filter(x => x[prop] == max);
    }
    
    getMax(myArr,"bpg")
    

    One line version:

    myArr.filter( x => x["bpg"] == Math.max(...myArr.map(x => x["bpg"])) )
    

提交回复
热议问题