Sorting Array with JavaScript reduce function

后端 未结 9 836
南方客
南方客 2020-12-01 17:49

Often I study some JavaScript interview questions, suddenly I saw a question about usage of reduce function for sorting an Array, I r

9条回答
  •  粉色の甜心
    2020-12-01 18:52

    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.

提交回复
热议问题