shfshanyue / Daily-Question

互联网大厂内推及大厂面经整理,并且每天一道面试题推送。每天五分钟,半年大厂中
https://q.shanyue.tech
4.92k stars 510 forks source link

【Q628】实现一个函数 maxBy,根据给定条件找到最大的数组项 #646

Open shfshanyue opened 3 years ago

shfshanyue commented 3 years ago

类似 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)

相关问题:

shfshanyue commented 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]])
}
haotie1990 commented 3 years ago
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;
}