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
Release: 2024-12-19 18:49:10
Original
763 people have browsed it

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

    1

    2

    3

    4

    5

    6

    7

    8

    [

        ['Anne', 'a'],

        ['Bob', 'b'],

        ['Henry', 'b'],

        ['Andrew', 'd'],

        ['Jason', 'c'],

        ['Thomas', 'b']

    ]

    Copy after login
  • sortingArr: A sorted array of group names, e.g.:

    1

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

    Copy after login

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

itemsArray.sort(function(a, b){ 

  return sortingArr.indexOf(a) - sortingArr.indexOf(b);

});

Copy after login

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

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

Copy after login

Output:

After sorting, the itemsArray will look like this:

1

2

3

4

5

6

7

8

[

    ['Bob', 'b'],

    ['Jason', 'c'],

    ['Henry', 'b'],

    ['Thomas', 'b'],

    ['Anne', 'a'],

    ['Andrew', 'd'],

]

Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template