【问题标题】:How to find the shortest element in an array with the reduce method如何使用reduce方法找到数组中最短的元素
【发布时间】:2018-02-08 03:37:00
【问题描述】:
我对这里的“.reduce”实现不满意。这个问题的目标是返回数组中最短单词的长度(注意不是单词本身!)。由于我们需要为累加器的第一次调用设置一个非常大的值,以允许 .reduce 将单词的长度与累加器进行比较,我使用了“Infinity”......有没有更好/更优雅的使用 .reduce 的方法这里?谢谢
function getLengthOfShortestElement(arr) {
return arr.reduce(function(acc, element) {
if (element.length < acc) {
acc = element.length;
}
return acc;
},Infinity);
}
【问题讨论】:
标签:
reduce
infinity
accumulator
【解决方案1】:
我认为您的解决方案很好。但是,如果像这样使用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')
【解决方案2】:
虽然@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)。