Sorting Array with JavaScript reduce function

后端 未结 9 846
南方客
南方客 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:34

    Array.sort mutates the array where using Array.reduce encourages a pure function. You could clone the array before sorting.

    I believe this question is designed to get you thinking differently by enforcing constraints. It tests your knowledge of how reduce works and as the answers show there are many ways to skin a cat. It'll show your personal flavour of js in solving this.

    I chose to use Array.findIndex and 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, []);
    

    Testing with the sample input produces

    arr.reduce(sortingReducer, [])
    // (17) [0, 3, 4, 4, 6, 7, 8, 11, 13, 23, 24, 52, 54, 59, 87, 91, 98]
    

提交回复
热议问题