极客时间返利平台,你可以在上边通过山月的链接购买课程,并添加我的微信 (shanyue94) 领取返现。
山月训练营之面试直通车 服务上线了,从准备简历、八股文准备、项目经历准备、面试、面经、面经解答、主观问题答复、谈薪再到入职的一条龙服务。

# 实现一个函数 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 (opens new window)

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;
}
Last Updated: 11/27/2021, 6:11:48 PM