Javascript - sort array based on another array

后端 未结 22 1778
鱼传尺愫
鱼传尺愫 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);

提交回复
热议问题