Sorting a JavaScript Array Based on Another Array
Arranging arrays in a specific order can be a challenging task, especially when you don't have IDs to rely on. Consider the following arrays:
itemsArray = [ ['Anne', 'a'], ['Bob', 'b'], ['Henry', 'b'], ['Andrew', 'd'], ['Jason', 'c'], ['Thomas', 'b'], ]; sortingArr = ['b', 'c', 'b', 'b', 'a', 'd'];
The goal is to rearrange itemsArray to match the order specified in sortingArr. Using a one-line solution, you can achieve this with:
itemsArray.sort(function(a, b) { return sortingArr.indexOf(a[1]) - sortingArr.indexOf(b[1]); });
Or, for even greater brevity:
itemsArray.sort((a, b) => sortingArr.indexOf(a[1]) - sortingArr.indexOf(b[1]));
This code utilizes array sorting functions to rearrange itemsArray based on the elements of sortingArr. The core idea is to sort the array based on the second element of each inner array (e.g., 'a', 'b', 'c', 'd'). By doing so, the items in itemsArray will align with the priorities defined in sortingArr.
The above is the detailed content of How to Sort a JavaScript Array Based on Another Array's Order?. For more information, please follow other related articles on the PHP Chinese website!