JS: Filter array of objects by max value per category

后端 未结 7 1531
北荒
北荒 2020-12-19 18:21

What is most efficient / elegant way to achieve sql-like filtering effect. I want to filter them and get only that objects which are max value in some group.

This is

7条回答
  •  孤城傲影
    2020-12-19 18:30

    Reduce the array to an object, using the name property as the key. For each item, check if the item that exists in the accumulator has a higher value than the current item, and if not replace it with the current item. Convert back to an array with Object.values():

    const arr = [{"name":"bathroom","value":54,"timeStamp":1562318089713},{"name":"bathroom","value":55,"timeStamp":1562318090807},{"name":"bedroom","value":48,"timeStamp":1562318092084},{"name":"bedroom","value":49,"timeStamp":1562318092223},{"name":"room","value":41,"timeStamp":1562318093467}]
    
    const result = Object.values(arr.reduce((r, o) => {
      r[o.name] = (r[o.name] && r[o.name].value > o.value) ? r[o.name] : o
    
      return r
    }, {}))
    
    console.log(result)

提交回复
热议问题