Home >Web Front-end >JS Tutorial >How to Sort a JavaScript Array Based on the Order of Another Array?

How to Sort a JavaScript Array Based on the Order of Another Array?

Barbara Streisand
Barbara StreisandOriginal
2024-12-19 18:49:10704browse

How to Sort a JavaScript Array Based on the Order of Another Array?

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.:

    [
        ['Anne', 'a'],
        ['Bob', 'b'],
        ['Henry', 'b'],
        ['Andrew', 'd'],
        ['Jason', 'c'],
        ['Thomas', 'b']
    ]
  • sortingArr: A sorted array of group names, e.g.:

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

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:

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

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:

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

Output:

After sorting, the itemsArray will look like this:

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

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn