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
Release: 2024-12-14 07:26:09
Original
201 people have browsed it

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'];
Copy after login

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]);
});
Copy after login

Or, for even greater brevity:

itemsArray.sort((a, b) => sortingArr.indexOf(a[1]) - sortingArr.indexOf(b[1]));
Copy after login

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!

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