Home >Web Front-end >JS Tutorial >How to Reorder 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!