JS: Filter array of objects by max value per category

后端 未结 7 1495
北荒
北荒 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:33

    What is most efficient / elegant way to achieve sql-like filtering effect.

    You could take functions for every step and pipe all functions for a single result.

    For example in SQL, you would have the following query:

    SELECT name, value, MAX(timeStamp) 
    FROM data 
    GROUP BY name;
    

    With an SQL like approach, you could group first and take the max object out of the result sets.

    result = pipe(
        groupBy('name'),
        select(max('timeStamp'))
    )(data);
    

    const
        pipe = (...functions) => input => functions.reduce((acc, fn) => fn(acc), input),
        groupBy = key => array => array.reduce((r, o) => {
            var temp = r.find(([p]) => o[key] === p[key])
            if (temp) temp.push(o);
            else r.push([o]);
            return r;
        }, []),
        max = key => array => array.reduce((a, b) => a[key] > b[key] ? a : b),
        select = fn => array => array.map(fn);
    
    
    var data = [{ 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 }],
        result = pipe(
            groupBy('name'),
            select(max('timeStamp'))
        )(data);
    
    console.log(result);
    .as-console-wrapper { max-height: 100% !important; top: 0; }

提交回复
热议问题