JS: Filter array of objects by max value per category

后端 未结 7 1529
北荒
北荒 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:31

    Doing this in stages.

    1. get a set of names
    2. create a sorted array in descending order
    3. then just map using find to get the first one

    Below is an example.

    const input = [{"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 output = [...new Set(input.map(m => m.name))].
      map(m => [...input].sort(
        (a,b) => b.value - a.value).
        find(x => m === x.name));
      
    console.log(output);

提交回复
热议问题