Sorting Array with JavaScript reduce function

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

    Here's an (imo) more elegant version of Jonas W's insertion sort solution. The callback just builds a new array of all lower values, the new one and all higher values. Avoids using explicit loops or indices, so it's easier to see at a glance that it works correctly.

    const insertValue = (arr, value) =>
      [...arr.filter(n => n <= value), value, ...arr.filter(n => n > value)]
    
    const testArr = [91, 4, 6, 24, 8, 7, 59, 3, 13, 0, 11, 98, 54, 23, 52, 87, 4]
    
    console.log(testArr.reduce(insertValue, []))

提交回复
热议问题