How to usea Temporary Array in Javascript

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' ]




JavaScript Program to Reorder an Array According to Given Indexes

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:

Table of Content

  • Using the map method
  • Creating a Custom Sorting Function
  • Swapping Elements in Place

We will explore all the above methods along with their basic implementation with the help of examples.

Similar Reads

Approach 1: Using the map method

...

Approach 2: Creating a Custom Sorting Function

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....

Approach 3: Swapping Elements in Place

In this approach, we will create a custom sorting function that utilizes the provided indexes to rearrange the elements....

Approach 4: Using a Temporary Array

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....

Contact Us