Javascript - sort array based on another array

后端 未结 22 1438
鱼传尺愫
鱼传尺愫 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条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-22 04:28

    var sortedArray = [];
    for(var i=0; i < sortingArr.length; i++) {
        var found = false;
        for(var j=0; j < itemsArray.length && !found; j++) {
            if(itemsArray[j][1] == sortingArr[i]) {
                sortedArray.push(itemsArray[j]);
                itemsArray.splice(j,1);
                found = true;
            }
        }
    }
    

    http://jsfiddle.net/s7b2P/

    Resulting order: Bob,Jason,Henry,Thomas,Anne,Andrew

提交回复
热议问题