Home > Web Front-end > JS Tutorial > How Can I Sort One Array Based on the Order of Another Array in JavaScript?

How Can I Sort One Array Based on the Order of Another Array in JavaScript?

Patricia Arquette
Release: 2024-12-23 01:18:11
Original
494 people have browsed it

How Can I Sort One Array Based on the Order of Another Array in JavaScript?

Rearranging Arrays Based on Auxiliary Values

In JavaScript, there may be scenarios where you need to sort one array based on the order specified by another array. This can be particularly useful when working with data structures where the order of elements is crucial.

Consider the following example:

itemsArray = [
    ['Anne', 'a'],
    ['Bob', 'b'],
    ['Henry', 'b'],
    ['Andrew', 'd'],
    ['Jason', 'c'],
    ['Thomas', 'b']
];
sortingArr = [ 'b', 'c', 'b', 'b', 'a', 'd' ];
Copy after login

In this case, the goal is to rearrange the itemsArray to match the order of the sortingArr. Unfortunately, there are no IDs to track the elements, so the priority is to match the order as closely as possible.

Solution:

To achieve this, you can leverage JavaScript's built-in sort() method in conjunction with a custom comparison function. The comparison function compares two elements from the itemsArray based on their corresponding values in the sortingArr.

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

This expression essentially sorts the itemsArray based on the corresponding indices of its elements in the sortingArr. As a result, the rearranged array will resemble the following:

itemsArray = [
    ['Bob', 'b'],
    ['Jason', 'c'],
    ['Henry', 'b'],
    ['Thomas', 'b']
    ['Anne', 'a'],
    ['Andrew', 'd'],
];
Copy after login

This solution prioritizes the order specified by the sortingArr and outputs the itemsArray in the desired arrangement.

The above is the detailed content of How Can I Sort One Array Based on the Order of Another Array in JavaScript?. 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