【问题标题】:return the smallest element in the array located in the given key返回数组中位于给定键中的最小元素
【发布时间】:2019-07-10 23:45:10
【问题描述】:

我想返回给定对象和键中的最小元素,但如果给定数组为空或给定键的属性不是数组,它应该返回 undefined。 我解决了它,但我对我的方法并不完全满意。 有什么建议可以缩短我的代码吗?

let obj = {
  key: [8, 5, 10, 15, 11, 21, 1, 25]
};

const smallest = (obj, key) => {
  return !Array.isArray(obj[key]) || obj[key].length <= 0 ? undefined : obj[key].reduce((l, s) => l < s ? l : s)
}
smallest(obj, 'key');

【问题讨论】:

  • 为了向后兼容:Math.min.apply(Math, obj[key])。但是我想知道为什么你会传递数组或空数组以外的东西?在调用smallest 之前,您可能不知道obj 中有什么?我的意思是,当根本没有数字时,要求最小的数字是很奇怪的。

标签: javascript


【解决方案1】:

您可以检查并返回最小值。

const smallest = (obj, key) => Array.isArray(obj[key]) && obj[key].length
    ? Math.min(...obj[key])
    : undefined;

console.log(smallest({ key: [8, 5, 10, 15, 11, 21, 1, 25] }, 'key'));
console.log(smallest({ key: [8] }, 'key'));
console.log(smallest({ key: [] }, 'key'));
console.log(smallest({}, 'key'));

【讨论】:

  • 嗨 Nina,我的意思是,如果您阅读了我的帖子,如果给定数组为空,则需要返回 undefined
【解决方案2】:

您可以在数组上使用Math.min()spread operator(...) 而不是reduce

let obj = {
  key: [8, 5, 10, 15, 11, 21, 1, 25]
};

const smallest = (obj, key) => {
  return !Array.isArray(obj[key]) || obj[key].length <= 0 ? undefined :  Math.min(...obj[key]);
}
console.log(smallest(obj, 'key'));

【讨论】:

  • 嗨,如果给定数组为空,它应该返回undefined
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-11-06
  • 2012-11-13
  • 2020-04-20
  • 2017-06-29
  • 1970-01-01
  • 2017-03-13
  • 2010-10-06
相关资源
最近更新 更多