Sorting a JavaScript Array Based on Another Array
In JavaScript, sorting arrays is a common operation. However, there are scenarios where you may want to sort an array based on another array. This can be challenging, especially when you don't have unique identifiers to link the elements.
Problem Statement:
Imagine you have two arrays:
itemsArray: An array of pairs [name, groupName], e.g.:
1 2 3 4 5 6 7 8 |
|
sortingArr: A sorted array of group names, e.g.:
1 |
|
The task is to rearrange itemsArray to match the arrangement of sortingArr. This means items belonging to the same group should be adjacent and ordered by the order in sortingArr.
Solution:
To solve this problem, we can use a sorting function that compares elements based on the index of their group in sortingArr:
1 2 3 |
|
This function calculates the difference between the indices of the elements in sortingArr. A positive difference indicates that element a should be placed after element b, while a negative difference indicates the opposite.
One-Line Solution:
Alternatively, you can write the sorting function using arrow syntax, resulting in a more concise solution:
1 |
|
Output:
After sorting, the itemsArray will look like this:
1 2 3 4 5 6 7 8 |
|
As you can see, the elements in the itemsArray have been rearranged and sorted to match the order in the sortingArr.
The above is the detailed content of How to Sort a JavaScript Array Based on the Order of Another Array?. For more information, please follow other related articles on the PHP Chinese website!