Javascript - sort array based on another array

后端 未结 22 1452
鱼传尺愫
鱼传尺愫 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:12

    this is probably too late but, you could also use some modified version of the code below in ES6 style. This code is for arrays like:

    var arrayToBeSorted = [1,2,3,4,5];
    var arrayWithReferenceOrder = [3,5,8,9];
    

    The actual operation :

    arrayToBeSorted = arrayWithReferenceOrder.filter(v => arrayToBeSorted.includes(v));
    

    The actual operation in ES5 :

    arrayToBeSorted = arrayWithReferenceOrder.filter(function(v) {
        return arrayToBeSorted.includes(v);
    });
    

    Should result in arrayToBeSorted = [3,5]

    Does not destroy the reference array.

提交回复
热议问题