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

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

Susan Sarandon
Susan SarandonOriginal
2024-12-13 04:55:14171browse

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

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

Consider a complex scenario where you need to reorganize an array (itemsArray) based on the sequence defined in another array (sortingArr). In this instance, there are no IDs to facilitate this adjustment.

To achieve this reordering, employ the following JavaScript code:

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

This concise code operates by comparing the positions of the respective elements in sortingArr. It calculates the difference between their positions and utilizes that difference to determine the new order within itemsArray.

For a more compact version, the following code accomplishes the same task:

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

By using these sorting techniques, you can effortlessly align the arrangement of itemsArray to match the desired sequence specified in sortingArr.

The above is the detailed content of How to Reorder 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