Sorting Array with JavaScript reduce function

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

    You can use an insertion sort:

    let array        = [91, 4, 6, 24, 8, 7, 59, 3, 13, 0, 11, 98, 54, 23, 52, 87, 4];
    let countIfLess  = (array,v)=> array.reduce((c,n)=>n array.reduce((c,n)=>n==v?c+1:c,0);
    
    console.log(
      array.reduce(
        (a,v,i,array)=>( a[countIfLess(array,v) + countIfEqual(a,v)]=v, a ),
        new Array(array.length)
      )
    );

    This will create the destination array once and then perform insertions into it at each step of the reduce without having to recreate the destination array.

    There are more efficient ways of implementing countIfEqual but I chose to implement all the functions using reduce rather than other array functions.

提交回复
热议问题