Open shfshanyue opened 3 years ago
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]])
}
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;
}
类似
loadash
如:面试追问:
相关问题: