DekGenius.com
JAVASCRIPT
anagram program in javascript
function checkStringsAnagram(a, b) {
let len1 = a.length;
let len2 = b.length;
if(len1 !== len2){
console.log('Invalid Input');
return
}
let str1 = a.split('').sort().join('');
let str2 = b.split('').sort().join('');
if(str1 === str2){
console.log("True");
} else {
console.log("False");
}
}
checkStringsAnagram("indian","ndiani")
anagram js
const isAnagram = (str1, str2) => {
const str2Arr = str2.split('');
for(let i = 0; i < str1.length; i++) {
const index = str2Arr.indexOf(str1[i]);
if(index === -1) return false;
str2Arr.splice(index, 1);
}
return !str2Arr.length;
}
javascript anagram
const s = "anagram"
const t = "nagaram"
const isAnagram = function(s, t) {
if (s.length !== t.length) {
return false
}
const map_s = new Map()
const map_t = new Map()
for (let i = 0; i < s.length; i++) {
if (map_s.has(s[i])) {
map_s.set(s[i], map_s.get(s[i]) + 1)
} else {
map_s.set(s[i], 1)
}
if (map_t.has(t[i])) {
map_t.set(t[i], map_t.get(t[i]) + 1)
} else {
map_t.set(t[i], 1)
}
}
for (const s of map_s) {
if (map_t.get(s[0]) !== s[1]) {
return false
}
}
console.log(map_s)
console.log(map_t)
// [Log]:
// Map(5) { 'a' => 3, 'n' => 1, 'g' => 1, 'r' => 1, 'm' => 1 }
// Map(5) { 'n' => 1, 'a' => 3, 'g' => 1, 'r' => 1, 'm' => 1 }
return true
};
console.log('
', isAnagram(s, t)) // [Log]: true
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;
}
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']);
anagram js
function isAnagram(stringA, stringB) {
// Sanitizing
stringA = stringA.toLowerCase().replace(/[W_]+/g, "");
stringB = stringB.toLowerCase().replace(/[W_]+/g, "");
// sorting
const stringASorted = stringA.split("").sort().join("");
const stringBSorted = stringB.split("").sort().join("");
return stringASorted === stringBSorted;
}
anagram javascript example
function anagram(name, words) {
name = name.toLowerCase().split('').sort().join('').trim();
words = words.join('').toLowerCase().split('').sort().join('');
return name === words;
}
anagram javascript
const isAnagram = (str1, str2) => {
const str2Arr = str2.split('');
for(let i = 0; i < str1.length; i++) {
const index = str2Arr.indexOf(str1[i]);
if(index === -1) return false;
str2Arr.splice(index, 1);
}
return !str2Arr.length;
}
console.log(isAnagram("abba","bbaa"))
© 2022 Copyright:
DekGenius.com