Often I study some JavaScript
interview questions, suddenly I saw a question about usage of reduce
function for sorting an Array
, I read about it in MDN and the usage of it in some medium
articles, But sorting an Array
is so Innovative:
const arr = [91,4,6,24,8,7,59,3,13,0,11,98,54,23,52,87,4];
I thought a lot, but I've no idea about how answer this question, how must be the reduce
call back
function? what is the initialValue
of reduce
function? and what are the accumulator
and currentValue
of call back
function of reduce
?
And at the end, Does this way have some benefits than other sorting algorithms? Or Is it useful to improve other algorithms?
sort
mutates the original array. Where usingreduce
will force you to use a pure a function. – Lex 16 hours agoreduce
for sorting is immutable action? – AmerllicA 16 hours agoreduce
– Patrick Roberts 15 hours agovar array = [1, 2, 3, 5, 6]; array.reduce(function diff (subtrahend, minuend, index, array) { array[index] -= subtrahend; return minuend })
will return6
but the original array will become[1, 1, 1, 2, 1]
– Patrick Roberts 15 hours agoreduce
can offer a pure alternative. – Lex 15 hours ago