JavaScript Program to Reorder an Array According to Given Indexes
Last Updated :
04 Jun, 2024
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 method
In this approach, we use the map
method to iterate over the indexes Array
. For each element in indexes Array
, the corresponding element from original Array
is fetched using the index value, and a new array is constructed with the rearranged elements.
Syntax:
function reorderArrayByIndexes(originalArray, indexesArray) {
return indexesArray.map();
}
Example: In this example, the reorderArrayByIndexes function maps originalArray elements using indexesArray, producing the reordered array.
JavaScript
function reorderArrayByIndexes(originalArray, indexesArray) {
return indexesArray.map(
index => originalArray[index]);
}
const originalArray =
['HTML', 'CSS', 'JavaScript', 'React.js'];
const indexesArray = [3, 1, 2, 0];
const reorderedArray =
reorderArrayByIndexes(originalArray, indexesArray);
console.log(reorderedArray);
Output[ 'React.js', 'CSS', 'JavaScript', 'HTML' ]
Approach 2: Creating a Custom Sorting Function
In this approach, we will create a custom sorting function that utilizes the provided indexes to rearrange the elements.
Syntax:
function reorderArrayByIndexes(originalArray, indexesArray) {
return originalArray.slice().sort((a, b) => {
// code implemantation...
});
}
Example: In this example, the reorderArrayByIndexes function sorts originalArray using indexesArray. It maps elements based on their indexes, producing the reordered array.
JavaScript
function reorderArrayByIndexes(originalArray, indexesArray) {
return originalArray.slice().sort((a, b) => {
const indexA =
indexesArray.indexOf(originalArray.indexOf(a));
const indexB =
indexesArray.indexOf(originalArray.indexOf(b));
return indexA - indexB;
});
}
const originalArray =
['HTML', 'CSS', 'Javascript', 'Node.js'];
const indexesArray = [3, 1, 2, 0];
const reorderedArray =
reorderArrayByIndexes(originalArray, indexesArray);
console.log(reorderedArray);
Output[ 'Node.js', 'CSS', 'Javascript', 'HTML' ]
Approach 3: Swapping Elements in Place
Swapping 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]]
// Where m and n are the index numbers to swap
Example: In this example, the reorderArrayByIndexes function reorders originalArray using indexesArray, swapping elements to their respective positions.
JavaScript
function reorderArrayByIndexes(originalArray, indexesArray) {
for (let i = 0; i < indexesArray.length; i++) {
while (indexesArray[i] !== i) {
const currentIndex = indexesArray[i];
[originalArray[i], originalArray[currentIndex]] =
[originalArray[currentIndex], originalArray[i]];
[indexesArray[i], indexesArray[currentIndex]] =
[indexesArray[currentIndex], indexesArray[i]];
}
}
return originalArray;
}
const originalArray =
['HTML', 'CSS', 'JavaScript', 'Bootstrap'];
const indexesArray = [3, 1, 2, 0];
const reorderedArray =
reorderArrayByIndexes(originalArray, indexesArray);
console.log(reorderedArray);
Output[ 'Bootstrap', 'CSS', 'JavaScript', 'HTML' ]
Approach 4: Using a Temporary Array
In 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.
JavaScript
function reorderArrayByIndexes(originalArray, indexesArray) {
const tempArray = new Array(originalArray.length);
indexesArray.forEach((index, i) => {
tempArray[index] = originalArray[i];
});
return tempArray;
}
const originalArray = ['HTML', 'CSS', 'JavaScript', 'Vue.js'];
const indexesArray = [2, 0, 3, 1];
const reorderedArray = reorderArrayByIndexes(originalArray, indexesArray);
console.log(reorderedArray);
Output[ 'CSS', 'Vue.js', 'HTML', 'JavaScript' ]
Similar Reads
JavaScript Program to Rearrange Array Alternately
Rearranging an array alternately means, If we have a sorted array then we have to rearrange the array such that the first largest element should come at index-0(0-based indexing), first smallest element should come at index-1, similarly, second largest element should come at index-3 and second small
7 min read
JavaScript Program to Sort the 2D Array Across Rows
We will see how to sort the 2D Array across rows using a Javascript program. we can sort the 2D Array Across Rows in many ways including Bubble Sort Algorithm, Array.prototype.sort() method, Insertion Sort Algorithm, Using the Selection Sort Algorithm, and Merge Sort Algorithm. Example: Input:[[8 5
6 min read
JavaScript Program for Insertion Sort
What is Insertion Sort Algorithm?Insertion sorting is one of the sorting techniques that is based on iterating the array and finding the right position for every element. It compares the current element to the predecessors, if the element is small compare it with the elements before. Move ahead to a
4 min read
JavaScript Program to Rearrange Array such that Even Positioned are Greater than Odd
In this article, we will cover rearranging arrays such that even positions are greater than odd in JavaScript. Give there is an array that we need to rearrange in the pattern where the even positioned are greater than the odd positioned in JavaScript. We will see the code for each approach along wit
4 min read
JavaScript Program to Find Minimum Number of Swaps to Sort Array
The minimum number of swaps to sort an array is the smallest quantity of element swaps needed to arrange the array in ascending or descending order. This minimizes the number of exchanges and is a key metric in sorting algorithms, as reducing swaps often improves efficiency and performance when orga
7 min read
Javascript Program to Interchange elements of first and last rows in matrix
Given a 4 x 4 matrix, we have to interchange the elements of first and last row and show the resulting matrix.Examples : Input : 3 4 5 0 2 6 1 2 2 7 1 2 2 1 1 2Output : 2 1 1 2 2 6 1 2 2 7 1 2 3 4 5 0Input : 9 7 5 1 2 3 4 1 5 6 6 5 1 2 3 1Output : 1 2 3 1 2 3 4 1 5 6 6 5 9 7 5 1The approach is very
2 min read
JavaScript Program to Sort Words in Alphabetical Order
Sorting words in alphabetical order involves arranging them based on the standard sequence of letters in the alphabet. This process helps in organizing data, making searches efficient, and presenting information in a clear and systematic manner.Methods to sort wordsTable of Content Approach 1: Using
5 min read
JavaScript Program for Selection Sort
What is Selection Sort in JavaScript?Selection sort is a simple and efficient algorithm that works on selecting either the smallest or the largest element of the list or array and moving it to the correct position. Working of Selection SortConsider the following arrayarr = [ 64, 25, 12, 22, 11]This
3 min read
JavaScript Program for Quick Sort
What is Quick Sort Algorithm?Quick sort is one of the sorting algorithms that works on the idea of divide and conquer. It takes an element as a pivot and partitions the given array around that pivot by placing it in the correct position in the sorted array. The pivot element can be selected in the f
4 min read
JavaScript Program to Find Lexicographically Next Permutation
Given an array of distinct integers, we want to find the lexicographically next permutation of those elements. In simple words, when all the possible permutations of an array are placed in a sorted order, it is the lexicographic order of those permutations. In this case, we have to find the next gre
5 min read