Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Map anagrams to one another in JavaScript
One array is an anagram of another if we can rearrange the elements of that array to achieve the other array.
For example:
[1, 2, 3] and [2, 1, 3] are anagrams of each other.
We need to write a JavaScript function that takes two anagram arrays and returns a mapping array. The mapping array contains the index of each element from the first array as it appears in the second array.
Problem 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];
This means:
- Item at index 0 in arr1 (23) is at index 1 in arr2
- Item at index 1 in arr1 (39) is at index 4 in arr2
- Item at index 2 in arr1 (57) is at index 3 in arr2
- And so on...
Using Nested Loops
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);
break; // Exit inner loop once found
}
}
}
return res;
};
console.log(anagramMappings(arr1, arr2));
[ 1, 4, 3, 2, 0 ]
Using indexOf() Method
A more concise approach uses the built-in indexOf() method:
const arr1 = [23, 39, 57, 43, 61];
const arr2 = [61, 23, 43, 57, 39];
const anagramMappingsIndexOf = (arr1 = [], arr2 = []) => {
return arr1.map(element => arr2.indexOf(element));
};
console.log(anagramMappingsIndexOf(arr1, arr2));
[ 1, 4, 3, 2, 0 ]
Comparison
| Method | Time Complexity | Code Length |
|---|---|---|
| Nested Loops | O(n²) | More verbose |
| indexOf() with map() | O(n²) | More concise |
Conclusion
Both approaches solve the anagram mapping problem effectively. The indexOf() method provides cleaner, more readable code while maintaining the same functionality.
Advertisements
