Javascript - sort array based on another array

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

    You could try this method.

    const sortListByRanking = (rankingList, listToSort) => {
      let result = []
    
      for (let id of rankingList) {
        for (let item of listToSort) {
          if (item && item[1] === id) {
            result.push(item)
          }
        }
      }
    
      return result
    }
    
    0 讨论(0)
  • 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);
    
    0 讨论(0)
  • 2020-11-22 04:07

    with numerical sortingArr:

    itemsArray.sort(function(a, b){  
      return sortingArr[itemsArray.indexOf(a)] - sortingArr[itemsArray.indexOf(b)];
    });
    
    0 讨论(0)
  • 2020-11-22 04:07

    Use the $.inArray() method from jQuery. You then could do something like this

    var sortingArr = [ 'b', 'c', 'b', 'b', 'c', 'd' ];
    var newSortedArray = new Array();
    
    for(var i=sortingArr.length; i--;) {
     var foundIn = $.inArray(sortingArr[i], itemsArray);
     newSortedArray.push(itemsArray[foundIn]);
    }
    
    0 讨论(0)
  • 2020-11-22 04:09
    let a = ['A', 'B', 'C' ]
    
    let b = [3, 2, 1]
    
    let c = [1.0, 5.0, 2.0]
    
    // these array can be sorted by sorting order of b
    
    const zip = rows => rows[0].map((_, c) => rows.map(row => row[c]))
    
    const sortBy = (a, b, c) => {
      const zippedArray = zip([a, b, c])
      const sortedZipped = zippedArray.sort((x, y) => x[1] - y[1])
    
      return zip(sortedZipped)
    }
    
    sortBy(a, b, c)
    
    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题