- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 −
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 ]
- Related Articles
- Are the strings anagrams in JavaScript
- Checking for string anagrams JavaScript
- Java Program to copy all the key-value pairs from one Map into another
- Grouping words with their anagrams in JavaScript
- Map numbers to characters in JavaScript
- Object to Map conversion in JavaScript
- How to pass event objects from one function to another in JavaScript?
- Filter one array with another array - JavaScript
- Map object in JavaScript.
- JavaScript: How to map array values without using "map" method?
- How to add properties from one object into another without overwriting in JavaScript?
- Map Sum Pairs in JavaScript
- Convert object to a Map - JavaScript
- How to create an image map in JavaScript?
- Group Anagrams in Python

Advertisements