如何使用reduce方法查找数组中的最短元素

时间:2017-08-30 12:12:43

标签: reduce infinity accumulator

我不满意我在这里实施'.reduce'。这个问题的目标是返回数组中最短单词的长度(而不是单词本身!)。因为我们需要为累加器的第一次调用设置一个非常大的值来允许.reduce将字的长度与累加器进行比较我使用了'Infinity'...是否有更好/更优雅的方式使用.reduce这里?感谢

    function getLengthOfShortestElement(arr) {

     return arr.reduce(function(acc, element) {
      if (element.length < acc) {
          acc = element.length;
      }
     return acc;
     },Infinity);
     }

2 个答案:

答案 0 :(得分:0)

我认为您的解决方案很好。但是如果像这样使用Infinity困扰你,你可以将初始累加器设置为零。然后你的第一个元素将是第一遍的新累加器。

示例:

function getLengthOfShortestElement(arr) {
  return arr.reduce(function(acc, element, index) {
    if (index == 0) {
        return element.length
    } else {
      if (element.length < acc) {
        acc = element.length;
      }
      return acc;    
    }
  }, 0);
}

const list1 = ['house', 'california', 'ant']
const list2 = ['ant', 'california', 'house']
const list3 = ['', 'a', 'cc']

console.log('running tests')
console.assert(getLengthOfShortestElement(list1) === 3 , 'list1 wrong')
console.assert(getLengthOfShortestElement(list2) === 3 , 'list2 wrong')
console.assert(getLengthOfShortestElement(list3) === 0 , 'list3 wrong')
console.log('done with tests')

答案 1 :(得分:0)

虽然@ Kevin的评估是正确的,但我发现自己对此不满意,因为它在循环的每次迭代中引入了额外的逻辑(额外的if)。

选择一个好的初始值更清晰。您可以使用Infinity,但也可以使用第一个元素的长度。

function getLengthOfShortestElement(arr) {
  return arr.reduce(
    function(acc, element) {
      if (element.length < acc) {
        acc = element.length;
      }
      return acc;
    },
    arr.length ? arr[0].length : 0
  );
}

这使得额外的条件逻辑保持在O(1)。