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

How to Sort a JavaScript Array Based on Another Array's Order?

Susan Sarandon
Susan SarandonOriginal
2024-12-14 07:26:09206browse

How to Sort a JavaScript Array Based on Another Array's Order?

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!

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