首页 > 其他分享 >js实现lodash的 keyBy 和 maxBy

js实现lodash的 keyBy 和 maxBy

时间:2022-08-25 10:44:46浏览次数:91  
标签:acc return lodash maxBy keyBy list value

// keyBy
function keyBy(list, by) {
    return list.reduce((acc, x) => {
        acc[by(x)] = x;
        return acc;
    }, {});
}
console.log(
    keyBy(
        [
            { id: 1, name: "beilei" },
            { id: 2, name: "xinqing" },
        ],
        (x) => x.id
    )
);
// maxBy
const maxByData = [{ value: 6 }, { value: 2 }, { value: 4 }];
function maxBy(list, keyBy) {
    return list.reduce((x, y) => {
        return keyBy(x) > keyBy(y) ? x : y;
    });
}

console.log(maxBy(maxByData, (x) => x.value));
// maxBy 返回数组,可能有多个符合条件的对象
function maxByArr(list, keyBy) {
    return list.reduce(
        (acc, x) => {
            if (keyBy(x) > keyBy(acc[0])) {
                return [x];
            }
            if (keyBy(x) === keyBy(acc[0])) {
                return [...acc, x];
            }
            return acc;
        },
        [list[0]]
    );
}
console.log(maxByArr(maxByData, (x) => x.value));

参考链接:https://github.com/shfshanyue/Daily-Question/issues/646

标签:acc,return,lodash,maxBy,keyBy,list,value
From: https://www.cnblogs.com/beileixinqing/p/16623467.html

相关文章

  • laravel collection keyBy 多字段
    1、场景二维数组中,如果要取出满足多个字段条件的数据时,通常使用遍历的方式。laravel提供collectionkeyBy可以将多个字段格式化作为键名,不用写foreach遍历。2、例子......