javascript sort sparse array keep indexes

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

    // Update for your needs ('position' to your key).
    
    function updateIndexes( list ) {
    
        list.sort( ( a, b ) => a.position - b.position )
    
        list.forEach( ( _, index, arr ) => {
    
            arr[ index ].position = index
    
        } )
    
    }
    
    var myList = [
       { position: 8 },
       { position: 5 },
       { position: 1 },
       { position: 9 }
    ]
    
    updateIndexes( myList )
    
    // Result:
    
    var myList = [
       { position: 1 },
       { position: 2 },
       { position: 3 },
       { position: 4 }
    ]
    

提交回复
热议问题