Javascript - sort array based on another array

后端 未结 22 1489
鱼传尺愫
鱼传尺愫 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
    2020-11-22 04:20

    I would use an intermediary object (itemsMap), thus avoiding quadratic complexity:

    function createItemsMap(itemsArray) { // {"a": ["Anne"], "b": ["Bob", "Henry"], …}
      var itemsMap = {};
      for (var i = 0, item; (item = itemsArray[i]); ++i) {
        (itemsMap[item[1]] || (itemsMap[item[1]] = [])).push(item[0]);
      }
      return itemsMap;
    }
    
    function sortByKeys(itemsArray, sortingArr) {
      var itemsMap = createItemsMap(itemsArray), result = [];
      for (var i = 0; i < sortingArr.length; ++i) {
        var key = sortingArr[i];
        result.push([itemsMap[key].shift(), key]);
      }
      return result;
    }
    

    See http://jsfiddle.net/eUskE/

提交回复
热议问题