Javascript - sort array based on another array

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

    Case 1: Original Question (No Libraries)

    Plenty of other answers that work. :)

    Case 2: Original Question (Lodash.js or Underscore.js)

    var groups = _.groupBy(itemArray, 1);
    var result = _.map(sortArray, function (i) { return groups[i].shift(); });
    

    Case 3: Sort Array1 as if it were Array2

    I'm guessing that most people came here looking for an equivalent to PHP's array_multisort (I did) so I thought I'd post that answer as well. There are a couple options:

    1. There's an existing JS implementation of array_multisort(). Thanks to @Adnan for pointing it out in the comments. It is pretty large, though.

    2. Write your own. (JSFiddle demo)

    function refSort (targetData, refData) {
      // Create an array of indices [0, 1, 2, ...N].
      var indices = Object.keys(refData);
    
      // Sort array of indices according to the reference data.
      indices.sort(function(indexA, indexB) {
        if (refData[indexA] < refData[indexB]) {
          return -1;
        } else if (refData[indexA] > refData[indexB]) {
          return 1;
        }
        return 0;
      });
    
      // Map array of indices to corresponding values of the target array.
      return indices.map(function(index) {
        return targetData[index];
      });
    }
    

    3. Lodash.js or Underscore.js (both popular, smaller libraries that focus on performance) offer helper functions that allow you to do this:

        var result = _.chain(sortArray)
          .pairs()
          .sortBy(1)
          .map(function (i) { return itemArray[i[0]]; })
          .value();
    

    ...Which will (1) group the sortArray into [index, value] pairs, (2) sort them by the value (you can also provide a callback here), (3) replace each of the pairs with the item from the itemArray at the index the pair originated from.

提交回复
热议问题