How to sort an array efficiently

后端 未结 4 443
鱼传尺愫
鱼传尺愫 2021-01-28 01:46

I\'m trying to sort an array [3,3,2,1,3,2,2,2,1] to [1,1,3,3,3,2,2,2,2].

I\'m trying to handle it using object, using the number as key, and th

4条回答
  •  梦如初夏
    2021-01-28 02:31

    You could get the count for sorting the array.

    const sortNums = array => {
        const count = {};
        for (let v of array) count[v] = (count[v] || 0) + 1;
        return array.sort((a, b) => count[a] - count[b] || a - b);
    }
    
    console.log(sortNums([3, 3, 2, 1, 3, 2, 1]));

    An approach by using the object for sorting.

    const sortNums = array => {
        var count = {},
            result = {};
        for (let v of array) (count[v] = count[v] || []).push(v);
        for (let a of Object.values(count)) (result[a.length] = result[a.length] || []).push(a);
        return Object.values(result).flat(Infinity)
    }
    
    console.log(sortNums([3, 3, 2, 1, 3, 2, 1]));

提交回复
热议问题