anagram in javascript without es6 code example
Example 1: anagram program in javascript
function group_anagrams(arr) {
let sortedArr = arr.map(item => item.split('').sort().join(''));
let setArr = new Set(sortedArr);
let reducedObj = {};
for (let setItem of setArr) {
let indexArr = sortedArr.reduce((acc, cur, index) => {
if (setItem === cur) {
acc.push(index);
}
return acc;
}, []);
reducedObj[setItem] = indexArr;
}
let finalArr = [];
for (let reduceItem in reducedObj) {
finalArr.push(reducedObj[reduceItem].map(item => arr[item]));
}
return finalArr;
}
group_anagrams(['car','cra','rca', 'cheese','ab','ba']);
Example 2: anagram javascript example
function anagram(name, words) {
var a = name.replace(/\s/g,'').toLowerCase().split('').sort().join('');
var b = words.join('').split('').sort().join('');
return a == b;
}