经常研究一些JavaScript
的面试题,突然看到一个关于reduce
函数对Array
排序的用法的题,我看了它在 MDN以及它在一些 medium
文章中的用法,但是对 Array
进行排序是如此创新:
const arr = [91,4,6,24,8,7,59,3,13,0,11,98,54,23,52,87,4];
我想了很多,但我不知道如何回答这个问题,reduce
call back
函数必须如何? reduce
函数的 initialValue
是什么? reduce
的call back
函数的accumulator
和currentValue
是什么?
最后,这种方式是否比其他排序算法有一些好处?或者对改进其他算法有用吗?
最佳答案
在这里使用 reduce 是没有意义的,但是您可以使用一个新数组作为累加器并对所有元素进行插入排序:
array.reduce((sorted, el) => {
let index = 0;
while(index < sorted.length && el < sorted[index]) index++;
sorted.splice(index, 0, el);
return sorted;
}, []);
这是没有 reduce 的版本:
array.sort((a, b) => a - b);
现在是编写 reducer 的一些一般技巧:
how must be the reduce call back function?
您要么采用累加器的方法,然后 reducer 应根据当前元素对累加器应用修改并将其返回:
(acc, el) => acc
或者如果累加器和元素具有相同的类型并且逻辑上相等,则不需要区分它们:
(a, b) => a + b
what is the initialValue of reduce function?
您应该问问自己“当它应用于空数组时应该减少什么?”
Now the most important: When to use reduce? (IMO)
如果您想将数组的值归结为一个单一的值或对象。
关于javascript - 使用 JavaScript reduce 函数对数组进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50245957/