javascript sort sparse array keep indexes

前端 未结 4 561
野性不改
野性不改 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:26

    Here's one approach. It copies the defined array elements to a new array and saves their indexes. It sorts the new array and then puts the sorted results back into the indexes that were previously used.

    var a = [];
    a[0] = 3;
    a[1] = 2; 
    a[2] = 6; 
    a[7] = 4; 
    a[8] = 5;
    
    
    // sortFn is optional array sort callback function, 
    // defaults to numeric sort if not passed
    function sortSparseArray(arr, sortFn) {
        var tempArr = [], indexes = [];
        for (var i = 0; i < arr.length; i++) {
            // find all array elements that are not undefined
            if (arr[i] !== undefined) {
                tempArr.push(arr[i]);    // save value
                indexes.push(i);         // save index
            }
        }
        // sort values (numeric sort by default)
        if (!sortFn) {
            sortFn = function(a,b) {
                return(a - b);
            }
        }
        tempArr.sort(sortFn);
        // put sorted values back into the indexes in the original array that were used
        for (var i = 0; i < indexes.length; i++) {
            arr[indexes[i]] = tempArr[i];
        }
        return(arr);
    }
    

    Working demo: http://jsfiddle.net/jfriend00/3ank4/

提交回复
热议问题