javascript sort sparse array keep indexes

前端 未结 4 560
野性不改
野性不改 2021-02-02 07:51

What is the best method to sort a sparse array and keep the elements on the same indexes? For example:

a[0] = 3, 
a[1] = 2, 
a[2] = 6,
a[7] = 4,
a[8] = 5,
         


        
4条回答
  •  南笙
    南笙 (楼主)
    2021-02-02 08:25

    You can

    1. Use filter or Object.values to obtain an array with the values of your sparse array.
    2. Then sort that array, from largest to smaller. Be aware it's not stable, which may be specially problematic if some values are not numeric. You can use your own sorting implementation.
    3. Use map and pop to obtain the desired array. Assign it to a.
    var b = a.filter(function(x) {
        return true;
    }).sort(function(x,y) {
        return y - x;
    });
    a = a.map([].pop, b);
    

    Or, in ECMAScript 2017,

    a = a.map([].pop, Object.values(a).sort((x,y) => y-x));
    

提交回复
热议问题