Javascript - sort array based on another array

后端 未结 22 1440
鱼传尺愫
鱼传尺愫 2020-11-22 03:45

Is it possible to sort and rearrange an array that looks like this:

itemsArray = [ 
    [\'Anne\', \'a\'],
    [\'Bob\', \'b\'],
    [\'Henry\', \'b\'],
             


        
22条回答
  •  抹茶落季
    2020-11-22 04:05

    let sortedOrder = [ 'b', 'c', 'b', 'b' ]
    let itemsArray = [ 
        ['Anne', 'a'],
        ['Bob', 'b'],
        ['Henry', 'b'],
        ['Andrew', 'd'],
        ['Jason', 'c'],
        ['Thomas', 'b']
    ]
    a.itemsArray(function (a, b) {
        let A = a[1]
        let B = b[1]
    
        if(A != undefined)
            A = A.toLowerCase()
    
        if(B != undefined)
            B = B.toLowerCase()
    
        let indA = sortedOrder.indexOf(A)
        let indB = sortedOrder.indexOf(B)
    
        if (indA == -1 )
            indA = sortedOrder.length-1
        if( indB == -1)
            indB = sortedOrder.length-1
    
        if (indA < indB ) {
            return -1;
        } else if (indA > indB) {
            return 1;
        }
        return 0;
    })
    

    This solution will append the objects at the end if the sorting key is not present in reference array

提交回复
热议问题