Javascript - sort array based on another array

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

    For getting a new ordered array, you could take a Map and collect all items with the wanted key in an array and map the wanted ordered keys by taking sifted element of the wanted group.

    var itemsArray = [['Anne', 'a'], ['Bob', 'b'], ['Henry', 'b'], ['Andrew', 'd'], ['Jason', 'c'], ['Thomas', 'b']],
        sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ],
        map = itemsArray.reduce((m, a) => m.set(a[1], (m.get(a[1]) || []).concat([a])), new Map),
        result = sortingArr.map(k => (map.get(k) || []).shift());
    
    console.log(result);

    0 讨论(0)
  • 2020-11-22 04:27

    this should works:

    var i,search, itemsArraySorted = [];
    while(sortingArr.length) {
        search = sortingArr.shift();
        for(i = 0; i<itemsArray.length; i++) {
            if(itemsArray[i][1] == search) {
                itemsArraySorted.push(itemsArray[i]);
                break;
            }
        } 
    }
    
    itemsArray = itemsArraySorted;
    
    0 讨论(0)
  • 2020-11-22 04:28
    var sortedArray = [];
    for(var i=0; i < sortingArr.length; i++) {
        var found = false;
        for(var j=0; j < itemsArray.length && !found; j++) {
            if(itemsArray[j][1] == sortingArr[i]) {
                sortedArray.push(itemsArray[j]);
                itemsArray.splice(j,1);
                found = true;
            }
        }
    }
    

    http://jsfiddle.net/s7b2P/

    Resulting order: Bob,Jason,Henry,Thomas,Anne,Andrew

    0 讨论(0)
  • 2020-11-22 04:29

    ES6

    const arrayMap = itemsArray.reduce(
      (accumulator, currentValue) => ({
        ...accumulator,
        [currentValue[1]]: currentValue,
      }),
      {}
    );
    const result = sortingArr.map(key => arrayMap[key]);
    

    More examples with different input arrays

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