实现一个函数 maxBy,根据给定条件找到最大的数组项
更多描述 类似
loadash
如:
const data = [{ value: 6 }, { value: 2 }, { value: 4 }];
//=> { value: 6 }
maxBy(data, (x) => x.value);
面试追问:
- 如果最大的项有多个,则多个都返回,如下所示
const data = [{ value: 6 }, { value: 2 }, { value: 4 }, { value: 6 }];
//=> [{ value: 6 }, { value: 6 }]
maxBy(data, (x) => x.value);
相关问题:
Issue 欢迎在 Gtihub Issue 中回答此问题: Issue 646
Author 回答者: shfshanyue
const maxBy = (list, keyBy) =>
list.reduce((x, y) => (keyBy(x) > keyBy(y) ? x : y));
若需要返回多个项,则使用以下代码
const maxBy = (list, keyBy) => {
return list.slice(1).reduce(
(acc, x) => {
if (keyBy(x) > keyBy(acc[0])) {
return [x];
}
if (keyBy(x) === keyBy(acc[0])) {
return [...acc, x];
}
return acc;
},
[list[0]],
);
};
Author 回答者: haotie1990
function maxBy(array, keyBy) {
if (!array || !array.length) {
return null;
}
const length = array.length;
let max = array[0];
let result = [max];
for (let i = 1; i < length; i++) {
const value = array[i];
if (keyBy(max) === keyBy(value)) {
result.push(value);
} else if (keyBy(max) < keyBy(value)) {
max = value;
result = [max];
}
}
if (result.length === 1) {
return result[0];
}
return result;
}