# Map anagrams to one another in JavaScript

## Anagram arrays:

One array is an anagram of another if we can randomise the elements of that array to achieve the other array.

For example −

[1, 2, 3] and [2, 1, 3] are anagrams of each other.

Suppose, we have two arrays, arr1 and arr2 which are anagrams of each other.

We are required to write a JavaScript function that takes in these two arrays and returns a new mapping array of the same length as arr1 and arr2. The mapping array should contain the index of elements of the arr1 array as they are present in the arr2 array.

For example −

If the two input arrays are −

const arr1 = [23, 39, 57, 43, 61];
const arr2 = [61, 23, 43, 57, 39];

Then the output should be −

const output = [1, 4, 3, 2, 0];

because the item at index 0 in arr1 is at index 1 in arr2

item at index 1 in arr1 is at index 4 in arr2 and so on

## Example

The code for this will be −

Live Demo

const arr1 = [23, 39, 57, 43, 61];
const arr2 = [61, 23, 43, 57, 39];
const anagramMappings = (arr1 = [], arr2 = []) => {
const res = [];
for(let i = 0; i < arr1.length; i++) {
for(let j = 0; j < arr2.length; j++) {
if(arr1[i] == arr2[j]){
res.push(j);
};
};
};
return res;
};
console.log(anagramMappings(arr1, arr2));

## Output

And the output in the console will be −

[ 1, 4, 3, 2, 0 ]

Advertisements