我经常研究一些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
是什么
最后,这种方式是否比其他排序算法有一些好处?或者它对改进其他算法有用吗?
发布于 2018-05-09 13:44:49
在使用Array.reduce
鼓励使用纯函数的情况下,Array.sort
会改变数组。你可以在排序前克隆数组。
我相信这个问题的目的是通过强制约束来让你有不同的想法。它测试你对reduce
如何工作的了解,正如答案所示,有许多方法可以给猫剥皮。它将展示您在解决此问题时的js个人风格。
我选择使用Array.findIndex
和Array.splice
。
const sortingReducer = (accumulator, value) => {
const nextIndex = accumulator.findIndex(i => value < i );
const index = nextIndex > -1 ? nextIndex : accumulator.length;
accumulator.splice(index, 0, value);
return accumulator;
}
const input = [5,4,9,1];
const output = input.reduce(sortingReducer, []);
使用样本输入结果进行测试
arr.reduce(sortingReducer, [])
// (17) [0, 3, 4, 4, 6, 7, 8, 11, 13, 23, 24, 52, 54, 59, 87, 91, 98]
发布于 2018-05-09 18:35:21
下面是一个(国际海事组织)更优雅的Jonas W's插入排序解决方案。回调只是构建了一个包含所有较低值、新值和所有较高值的新数组。避免使用显式循环或索引,因此很容易一目了然地看到它是正确工作的。
const insertValue = (arr, value) =>
[...arr.filter(n => n <= value), value, ...arr.filter(n => n > value)]
const testArr = [91, 4, 6, 24, 8, 7, 59, 3, 13, 0, 11, 98, 54, 23, 52, 87, 4]
console.log(testArr.reduce(insertValue, []))
发布于 2018-05-09 15:22:01
如果没有提供数组,您可以使用一些函数来获取数组,通过接受两个参数来返回已排序数组的函数,以及通过使用另一个reduce方法来获取已排序数组的部分结果的排序回调。
const
getArray = a => Array.isArray(a) ? a : [a],
order = (a, b) => a < b ? [a, b] : [b, a],
sort = (a, b) => getArray(a).reduce((r, v) => r.concat(order(r.pop(), v)), [b]),
array = [91, 4, 6, 24, 8, 7, 59, 3, 13, 0, 11, 98, 54, 23, 52, 87, 4];
console.log(array.reduce(sort));
.as-console-wrapper { max-height: 100% !important; top: 0; }
https://stackoverflow.com/questions/50245957
复制相似问题