javascriptarrayssorting

Sort a JavaScript array based on another array


Is it possible to sort and rearrange an array that looks like the following?

itemsArray = [
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
]

to match the arrangement of this array:

sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]

Unfortunately, I don’t have any IDs to keep track on. I would need to priority the items-array to match the sortingArr as close as possible.

Here is the output I’m looking for:

itemsArray = [
    ['Bob', 'b'],
    ['Jason', 'c'],
    ['Henry', 'b'],
    ['Thomas', 'b']
    ['Anne', 'a'],
    ['Andrew', 'd'],
]

How can this be done?


Solution

  • One-Line answer.

    itemsArray.sort(function(a, b){  
      return sortingArr.indexOf(a) - sortingArr.indexOf(b);
    });
    

    Or even shorter:

    itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));
    

    To avoid mutating itemsArray, you can use toSorted (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/toSorted).

    const newArray = itemsArray.toSorted((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));