js实现lodash的 keyBy 和 maxBy

2022-08-28 14:05:03 浏览数 (3)

代码语言:javascript复制
// 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

0 人点赞