Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
7
rated 0 times [  9] [ 2]  / answers: 1 / hits: 39392  / 6 Years ago, wed, may 9, 2018, 12:00:00

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?


More From » algorithm

 Answers
4

It makes no sense to use reduce here, however you could use a new array as an accumulator and do insertion sort with all elements:


array.reduce((sorted, el) => {
let index = 0;
while(index < sorted.length && el < sorted[index]) index++;
sorted.splice(index, 0, el);
return sorted;
}, []);

Here is the version without reduce:


array.sort((a, b) => a - b);



Now some general tips for writing reducers:



how must be the reduce call back function?



You either take an approach with an accumulator, then the reducer should apply a modification to the accumulator based on the current element and return it:


(acc, el) => acc

Or if accumulator and the elements have the sane type and are logically equal, you dont need to distinguish them:


 (a, b) => a + b


what is the initialValue of reduce function?



You should ask yourself "What should reduce return when it is applied on an empty array?"



Now the most important: When to use reduce? (IMO)



If you want to boil down the values of an array into one single value or object.


[#54481] Friday, May 4, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
jaelyn

Total Points: 619
Total Questions: 102
Total Answers: 104

Location: Honduras
Member since Sun, Dec 26, 2021
2 Years ago
;