![]() |
Reordering an array according to given indexes means rearranging the elements of an array based on a separate array that specifies the desired order. Each element in the given index array corresponds to the index of the element in the original array at which it should be placed in the reordered array. This operation is useful when you need to sort or arrange elements in a specific custom order, different from the natural order of the elements. There are several methods that can be used to Reorder an array according to given indexes in JavaScript, which are listed below: We will explore all the above methods along with their basic implementation with the help of examples. Approach 1: Using the map methodIn this approach, we use the Syntax: function reorderArrayByIndexes(originalArray, indexesArray) { Example: In this example, the reorderArrayByIndexes function maps originalArray elements using indexesArray, producing the reordered array.
Output [ 'React.js', 'CSS', 'JavaScript', 'HTML' ] Approach 2: Creating a Custom Sorting FunctionIn this approach, we will create a custom sorting function that utilizes the provided indexes to rearrange the elements. Syntax: function reorderArrayByIndexes(originalArray, indexesArray) { Example: In this example, the reorderArrayByIndexes function sorts originalArray using indexesArray. It maps elements based on their indexes, producing the reordered array.
Output [ 'Node.js', 'CSS', 'Javascript', 'HTML' ] Approach 3: Swapping Elements in PlaceSwapping elements in place means exchanging the positions of two elements within an array without creating a new array. here we will swap elements within the original array, following the specified indexes. Syntax: [a[m], a[n]] = [a[n], a[m]] Example: In this example, the reorderArrayByIndexes function reorders originalArray using indexesArray, swapping elements to their respective positions.
Output [ 'Bootstrap', 'CSS', 'JavaScript', 'HTML' ] Approach 4: Using a Temporary ArrayIn this approach, we create a temporary array of the same length as the original array. We then iterate through the indexesArray and place each element from the originalArray into the correct position in the temporary array. Finally, we return the temporary array. Example: In this example, the reorderArrayByIndexes function reorders the originalArray using the indexesArray by placing elements into a temporary array based on the specified indexes.
Output [ 'CSS', 'Vue.js', 'HTML', 'JavaScript' ] |
Reffered: https://www.geeksforgeeks.org
JavaScript |
Type: | Geek |
Category: | Coding |
Sub Category: | Tutorial |
Uploaded by: | Admin |
Views: | 12 |