Is it possible to sort and rearrange an array that looks like this:
JavaScript
x
9
1
itemsArray = [
2
['Anne', 'a'],
3
['Bob', 'b'],
4
['Henry', 'b'],
5
['Andrew', 'd'],
6
['Jason', 'c'],
7
['Thomas', 'b']
8
]
9
to match the arrangement of this array:
JavaScript
1
2
1
sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ]
2
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.
Update:
Here is the output I’m looking for:
JavaScript
1
9
1
itemsArray = [
2
['Bob', 'b'],
3
['Jason', 'c'],
4
['Henry', 'b'],
5
['Thomas', 'b']
6
['Anne', 'a'],
7
['Andrew', 'd'],
8
]
9
Any idea how this can be done?
Advertisement
Answer
One-Line answer.
JavaScript
1
4
1
itemsArray.sort(function(a, b){
2
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
3
});
4
Or even shorter:
JavaScript
1
2
1
itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));
2