Javascript - sort array based on another array

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

    If you use the native array sort function, you can pass in a custom comparator to be used when sorting the array. The comparator should return a negative number if the first value is less than the second, zero if they're equal, and a positive number if the first value is greater.

    So if I understand the example you're giving correctly, you could do something like:

    function sortFunc(a, b) {
      var sortingArr = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
      return sortingArr.indexOf(a[1]) - sortingArr.indexOf(b[1]);
    }
    
    itemsArray.sort(sortFunc);
    

提交回复
热议问题