Sorting Array with JavaScript reduce function

AmerllicA picture AmerllicA · May 9, 2018 · Viewed 16.5k times · Source

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?

Answer

Jonas Wilms picture Jonas Wilms · May 9, 2018

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.