Counting odd and even numbers function issue - javascript

I want to provide function which will return object with odd and even numbers. Example: parseNum(12345) // Object{odd: 3, even:2}. I've got my code, but I don't understand why it's not working. Where is the problem?
function parseNum(num) {
var obj = {
odd: 0,
even: 0
};
var arr = Array.from(num);
arr.forEach(function(value) {
if (value % 2 === 0) {
obj.odd += 1;
} else {
obj.even += 1;
}
});
return obj;
}

Your answer is not working because a number is not iterable, you should cast it to string first.
function parseNum(num) {
var obj = {
odd: 0,
even: 0
};
if (typeof num === 'number') {
num = num.toString();
}
var arr = Array.from(num);
arr.forEach(function(value) {
if (value % 2 === 0) {
obj.odd += 1;
} else {
obj.even += 1;
}
});
return obj;
}

I think it's easier
function parseNum(num) {
const odd = Math.floor(num / 2);
const even = num - odd;
return {
odd,
even
}
}

Related

For loop without using for statement

I'm trying to write a program where you print a decrement by 1 loop, so if the value is 3 the output should be 3,2,1. But the output I get from this code is 3,2,1,0. Are there any ways I can fix this?
function loop(value) {
while(greaterThanZero(value) == true) {
printValue(value);
value = reduceOne(value);
console.log(value);
value--;
}
}
var value = 3;
var greaterThanZero = function (n) {
return n > 0;
}
var reduceOne = function (n) {
return n - 1;
}
var printValue = function (n) {
console.log(n)
}
You're doing the same thing twice in each iteration (logging and decrementing). Remove the two duplicate statements so you can break out immediately instead of going two at a time.
function loop(value) {
while(greaterThanZero(value) == true) {
console.log(value);
value--;
}
}
var greaterThanZero = function (n) {
return n > 0;
}
loop(3)
The function seems to be working as expected but you are seeing 0 because of this console.log(value). It is just logging the value after decrementing it
var value = 3;
var greaterThanZero = function(n) {
return n > 0;
}
var reduceOne = function(n) {
return n - 1;
}
var printValue = function(n) {
console.log(n)
}
function loop(value) {
while (greaterThanZero(value) == true) {
printValue(value);
value = reduceOne(value);
//console.log(value);
//value--;
}
}
loop(value)

Javascript how to optimise this count array values function

I have a function that mimics the array_count_values function from php in javascript but it's not very fast. I'm wondering if there's a way to fix it?
function array_count_values(arr) {
let a = [], prev;
arr.sort();
for ( let i = 0; i < arr.length; i++ ) {
if ( arr[i] !== prev ) {
a.push(1)
} else {
a[a.length-1]++;
}
prev = arr[i];
}
return a;
}
It just returns a simple array of numbers with the counts so like 2,1,2,1,1. The input in this case would be numeric arrays 5-7 elements long, so for example array_count_values([6,4,10,6,6])
You can use reduce to loop thru the array and count each entry.
function array_count_values(arr) {
return arr.reduce((c, v) => {
c[v] = c[v] || 0;
c[v]++;
return c;
}, {})
}
var result = array_count_values([6, 4, 10, 6, 6]);
console.log(result);
You could take an object for counting and omit sorting. This approach uses a single loop.
function array_count_values(array) {
var count = {},
i;
for (i = 0; i < array.length; i++) {
if (array[i] in count) {
count[array[i]]++;
} else {
count[array[i]] = 1;
}
}
return Object.values(count).sort((a, b) => b - a);
}
console.log(array_count_values([6, 4, 10, 6, 6]));
This is actually a straight-forward algorithm. I've been brushing up on them lately:
var array_count_values = function(array) {
let dict = {};
for (var i = 0; i < array.length; i++ ) {
var num = array[i];
(dict[num]) ? dict[num]++ : dict[num] = 1;
}
return dict;
}
console.log(array_count_values([6, 4, 10, 6, 6]));
Time and space complexity is both O(n).
I think the addition of a sort here is overkill, and probably the slowest part of this.
I think this will be the fastest/simplest way you can do this.
function array_count_values(arr) {
let outputCounts = {};
for ( let i = 0; i < arr.length; i++ ) {
if (outputCounts[arr[i]] != undefined){
outputCounts[arr[i]] += 1;
} else {
outputCounts[arr[i]] = 1;
}
}
return outputCounts;
}
The caveat here is that you're going to get an object back instead of an array as in your example.
const arr = [1, 2, 2, 3];
function array_count_values (arr) {
const frequencies = arr.reduce((f, v) => {
const freq = f.get(v) || 0;
f.set(v, freq + 1);
return f;
}, new Map());
return arr.map(v => frequencies.get(v));
}
console.log(array_count_values(arr));
Looking at how array_count_values works in php. This might be what you are looking for
function array_count_values(arr) {
return arr.reduce((acc, val) => {
if (!acc[val]) {
acc[val] = 0
}
acc[val] += 1
return acc
}, {})
}
To return an array as required in the question
function array_count_values(arr) {
return Object.values(arr.reduce((acc, val) => {
if (!acc[val]) {
acc[val] = 0
}
acc[val] += 1
return acc
}, {}))
}

Javascript: Function to fill an object with the vowels as the keys and the count as the values

As before, I have looked all over for the answer and I'm just a beginner and I am trying to learn from this and not just be handed the answer.
var voweler = function (str) {
var strArr = str.split('')
var obj = {};
for (var i = 0; i < strArr.length; i++) {
if (strArr[i] == 'a') {
obj.a = 0;
obj.a++;
} else if (strArr[i] == 'e') {
obj.e = 0;
obj.e++;
} else if (strArr[i] == 'i') {
obj.i = 0;
obj.i++;
} else if (strArr[i] == 'o') {
obj.o = 0;
obj.o++;
} else if (strArr[i] == 'u') {
obj.u = 0;
obj.u++;
}
};
return obj;
}
voweler("This is a test")
//returns this which is wrong. Object {i: 1, a: 1, e: 1}
Your code for updating the counts is wrong. Every vowel encountered, you run obj.<vowel> = 0 which resets the count! To remedy this, set the counts before you enter the for loop and then in the for loop, only increment the counter.
If you'd prefer to only have an entry if the vowel exists, you can conditionally increment:
if(strArr[i] == <some_vowel>){
if(obj.<some_vowel> === undefined)obj.<some_vowel> = 1;
else obj.<some_vowel> ++;
}
Couple of hints:
Your loop will assign the property value for the key to 0 every time the character is a vowel, before incrementing.
You can use toLowerCase() if you want to find upper and lower case vowels.
You can use indexOf. It will return -1 if it cannot find the argument in a string.
var voweler = function (str) {
var strArr = str.toLowerCase().split('');
var obj = {};
strArr.forEach(function(ch) {
if ('aeiou'.indexOf(ch) !== -1) {
obj[ch] = (obj[ch] || 0 ) + 1;
}
});
return obj;
}
console.log(voweler("This is a test"));
// Object {i: 2, a: 1, e: 1}
You might prefer something like this:
function voweler(input) {
var result = {
a: 0, e: 0, i: 0, o: 0, u: 0
};
for (var i = 0; i < input.length; i++) {
var char = input.charAt(i).toLowerCase();
if (result.hasOwnProperty(char)) {
result[char] ++;
}
}
return result;
}
Just because we can… and DTing has your answer already.
function countVowels(s) {
var vowels = /[aeiou]/,
o = {};
s.toLowerCase().split('').forEach(function(c){
if (vowels.test(c)) o.hasOwnProperty(c)? ++o[c] : o[c] = 1;
});
return o;
}
console.log(JSON.stringify(countVowels('hi there')));
There is also:
function countVowels(s) {
return (s.toLowerCase().match(/[aeiou]/g) || []).reduce(function(o, c) {
o[c] = (o[c] || 0) + 1;
return o;
}, {});
}

loop through array, returns odd and even numbers

I am teaching myself code and am trying to solve this problem:
Write a loop that loops through nums, if the item is even, it adds it to the evens array, if the item is odd, it adds it to the odds array.
This is what I have so far:
var nums = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var evens = [];
var odds = [];
var evenNumbers = function(nums) {
for (var i = 0; i < nums.length; i++) {
if ((nums[i] % 2) != 1) {
evens.push(nums[i]);
console.log(evens);
}
else {
odds.push(nums[i]);
console.log(odds);
}
}
};
alert(evens);
alert(odds);
They don't return anything and I'm not sure where I'm going wrong, any help would be much appreciated.
I would recommend checking out the array.prototype.filter function with ES6 syntax:
const oddNumbers = [1,2,34,54,55,34,32,11,19,17,54,66,13].filter((number) => number%2!==0);
console.log(oddNumbers);
So elegant :)
You're not actually executing the function. You need to call evenNumbers();
var nums = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var evens = [];
var odds = [];
var evenNumbers = function(nums) {
for (var i = 0; i < nums.length; i++) {
if ((nums[i] % 2) != 1) {
evens.push(nums[i]);
console.log(evens);
}
else {
odds.push(nums[i]);
console.log(odds);
}
}
};
evenNumbers(nums);
alert(evens);
alert(odds);
You aren't actually calling your function, just defining it.
call:
evenNumbers(nums);
before alerting the arrays
function groupNumbers(arr) {
var arr = [1,2,3,4,5,6,7,8,9,10];
var evenNumbers = arr.filter(number => number % 2 == 0);
console.log("Even numbers " + evenNumbers);
var oddNumbers = arr.filter(number => number % 2 !== 0);
console.log("Odd numbers " + oddNumbers);
}
groupNumbers();
var rsl = {even:[], odd:[]};
[1,2,34,54,55,34,32,11,19,17,54,66,13].forEach(function(val,key,arr)
{
var wrd = (val % 2) ? 'odd' : 'even';
rsl[wrd][rsl[wrd].length] = val;
});
console.log(rsl);
//Even odd
var arrays = [1,2,34,54,55,34,32,11,19,17,54,66,13];
var result = arrays.filter((numbers)=>{
if(numbers%2!==0){
console.log(`${numbers} is not even`);
} else {
console.log(`${numbers} is even`);
}
});
Here is a snippet :
const arr = [24,42,543,676,456,535,555];
console.log("Values: "+arr);
var even = arr.filter((number)=>number%2 === 0);
console.log("Even Number: "+even);
var odd = arr.filter((number)=>number % 2 !==0);
console.log("Odd Number: "+odd);
Someone can try according to the way:
function findOddEven(arr){
let odd=[],even=[],i=0,j=0,k=0;
for(i;i<arr.length;i++){
if(arr[i]%2==0){
even[j++]=arr[i]
}else{
odd[k++]=arr[i]
}
}
console.log("Even and Odd number",even,odd)
}
findOddEven([2,13,4,26,17])
function sortEvenOdd(arr, arrSize) {
let odd = [];
let even = [];
for (let i = arrSize - 1; i >= 0; i--) {
if (arr[i] % 2 !== 0) {
odd.push(arr[i]);
} else {
even.push(arr[i]);
}
}
even.sort(function (a, b) {
return a - b;
});
odd.sort(function (a, b) {
return b - a;
});
return [...odd, ...even];
}
// return odd and even numbers
/* Sample Input
7
1 2 3 5 4 7 10
Sample Output
7 5 3 1 2 4 10
Sample Input
7
0 4 5 3 7 2 1
Sample Output
7 5 3 1 0 2 4 */

JavaScript anagram comparison

I'm trying to compare two strings to see if they are anagrams.
My problem is that I'm only comparing the first letter in each string. For example, "Mary" and "Army" will return true but unfortunately so will "Mary" and Arms."
How can I compare each letter of both strings before returning true/false?
Here's a jsbin demo (click the "Console" tab to see the results"):
http://jsbin.com/hasofodi/1/edit
function compare (a, b) {
y = a.split("").sort();
z = b.split("").sort();
for (i=0; i<y.length; i++) {
if(y.length===z.length) {
if (y[i]===z[i]){
console.log(a + " and " + b + " are anagrams!");
break;
}
else {
console.log(a + " and " + b + " are not anagrams.");
break;
}
}
else {
console.log(a + " has a different amount of letters than " + b);
}
break;
}
}
compare("mary", "arms");
Instead of comparing letter by letter, after sorting you can join the arrays to strings again, and let the browser do the comparison:
function compare (a, b) {
var y = a.split("").sort().join(""),
z = b.split("").sort().join("");
console.log(z === y
? a + " and " + b + " are anagrams!"
: a + " and " + b + " are not anagrams."
);
}
If you want to write a function, without using inbuilt one, Check the below solution.
function isAnagram(str1, str2) {
if(str1 === str2) {
return true;
}
let srt1Length = str1.length;
let srt2Length = str2.length;
if(srt1Length !== srt2Length) {
return false;
}
var counts = {};
for(let i = 0; i < srt1Length; i++) {
let index = str1.charCodeAt(i)-97;
counts[index] = (counts[index] || 0) + 1;
}
for(let j = 0; j < srt2Length; j++) {
let index = str2.charCodeAt(j)-97;
if (!counts[index]) {
return false;
}
counts[index]--;
}
return true;
}
This considers case sensitivity and removes white spaces AND ignore all non-alphanumeric characters
function compare(a,b) {
var c = a.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
var d = b.replace(/\W+/g, '').toLowerCase().split("").sort().join("");
return (c ===d) ? "Anagram":"Not anagram";
}
Quick one-liner solution with javascript functions - toLowerCase(), split(), sort() and join():
Convert input string to lowercase
Make array of the string with split()
Sort the array alphabetically
Now join the sorted array into a string using join()
Do the above steps to both strings and if after sorting strings are the same then it will be anargam.
// Return true if two strings are anagram else return false
function Compare(str1, str2){
if (str1.length !== str2.length) {
return false
}
return str1.toLowerCase().split("").sort().join("") === str2.toLowerCase().split("").sort().join("")
}
console.log(Compare("Listen", "Silent")) //true
console.log(Compare("Mary", "arms")) //false
No need for sorting, splitting, or joining. The following two options are efficient ways to go:
//using char array for fast lookups
const Anagrams1 = (str1 = '', str2 = '') => {
if (str1.length !== str2.length) {
return false;
}
if (str1 === str2) {
return true;
}
const charCount = [];
let startIndex = str1.charCodeAt(0);
for (let i = 0; i < str1.length; i++) {
const charInt1 = str1.charCodeAt(i);
const charInt2 = str2.charCodeAt(i);
startIndex = Math.min(charInt1, charInt2);
charCount[charInt1] = (charCount[charInt1] || 0) + 1;
charCount[charInt2] = (charCount[charInt2] || 0) - 1;
}
while (charCount.length >= startIndex) {
if (charCount.pop()) {
return false;
}
}
return true;
}
console.log(Anagrams1('afc','acf'))//true
console.log(Anagrams1('baaa','bbaa'))//false
console.log(Anagrams1('banana','bananas'))//false
console.log(Anagrams1('',' '))//false
console.log(Anagrams1(9,'hey'))//false
//using {} for fast lookups
function Anagrams(str1 = '', str2 = '') {
if (str1.length !== str2.length) {
return false;
}
if (str1 === str2) {
return true;
}
const lookup = {};
for (let i = 0; i < str1.length; i++) {
const char1 = str1[i];
const char2 = str2[i];
const remainingChars = str1.length - (i + 1);
lookup[char1] = (lookup[char1] || 0) + 1;
lookup[char2] = (lookup[char2] || 0) - 1;
if (lookup[char1] > remainingChars || lookup[char2] > remainingChars) {
return false;
}
}
for (let i = 0; i < str1.length; i++) {
if (lookup[str1[i]] !== 0 || lookup[str2[i]] !== 0) {
return false;
}
}
return true;
}
console.log(Anagrams('abc', 'cba'));//true
console.log(Anagrams('abcc', 'cbaa')); //false
console.log(Anagrams('abc', 'cde')); //false
console.log(Anagrams('aaaaaaaabbbbbb','bbbbbbbbbaaaaa'));//false
console.log(Anagrams('banana', 'ananab'));//true
Cleanest and most efficient solution for me
function compare(word1, word2) {
const { length } = word1
if (length !== word2.length) {
return false
}
const charCounts = {}
for (let i = 0; i < length; i++) {
const char1 = word1[i]
const char2 = word2[i]
charCounts[char1] = (charCounts[char1] || 0) + 1
charCounts[char2] = (charCounts[char2] || 0) - 1
}
for (const char in charCounts) {
if (charCounts[char]) {
return false
}
}
return true
}
I modified your function to work.
It will loop through each letter of both words UNTIL a letter doesn't match (then it knows that they AREN'T anagrams).
It will only work for words that have the same number of letters and that are perfect anagrams.
function compare (a, b) {
y = a.split("").sort();
z = b.split("").sort();
areAnagrams = true;
for (i=0; i<y.length && areAnagrams; i++) {
console.log(i);
if(y.length===z.length) {
if (y[i]===z[i]){
// good for now
console.log('up to now it matches');
} else {
// a letter differs
console.log('a letter differs');
areAnagrams = false;
}
}
else {
console.log(a + " has a different amount of letters than " + b);
areAnagrams = false;
}
}
if (areAnagrams) {
console.log('They ARE anagrams');
} else {
console.log('They are NOT anagrams');
}
return areAnagrams;
}
compare("mary", "arms");
A more modern solution without sorting.
function(s, t) {
if(s === t) return true
if(s.length !== t.length) return false
let count = {}
for(let letter of s)
count[letter] = (count[letter] || 0) + 1
for(let letter of t) {
if(!count[letter]) return false
else --count[letter]
}
return true;
}
function validAnagramOrNot(a, b) {
if (a.length !== b.length)
return false;
const lookup = {};
for (let i = 0; i < a.length; i++) {
let character = a[i];
lookup[character] = (lookup[character] || 0) + 1;
}
for (let i = 0; i < b.length; i++) {
let character = b[i];
if (!lookup[character]) {
return false;
} else {
lookup[character]--;
}
}
return true;
}
validAnagramOrNot("a", "b"); // false
validAnagramOrNot("aza", "zaa"); //true
Here's my contribution, I had to do this exercise for a class! I'm finally understanding how JS works, and as I was able to came up with a solution (it's not - by far - the best one, but it's ok!) I'm very happy I can share this one here, too! (although there are plenty solutions here already, but whatever :P )
function isAnagram(string1, string2) {
// first check: if the lenghts are different, not an anagram
if (string1.length != string2.length)
return false
else {
// it doesn't matter if the letters are capitalized,
// so the toLowerCase method ensures that...
string1 = string1.toLowerCase()
string2 = string2.toLowerCase()
// for each letter in the string (I could've used for each :P)
for (let i = 0; i < string1.length; i++) {
// check, for each char in string2, if they are NOT somewhere at string1
if (!string1.includes(string2.charAt(i))) {
return false
}
else {
// if all the chars are covered
// and the condition is the opposite of the previous if
if (i == (string1.length - 1))
return true
}
}
}
}
First of all, you can do the length check before the for loop, no need to do it for each character...
Also, "break" breaks the whole for loop. If you use "continue" instead of "break", it skips the current step.
That is why only the first letters are compared, after the first one it quits the for loop.
I hope this helps you.
function compare (a, b) {
y = a.split("").sort();
z = b.split("").sort();
if(y.length==z.length) {
for (i=0; i<y.length; i++) {
if (y[i]!==z[i]){
console.log(a + " and " + b + " are not anagrams!");
return false;
}
}
return true;
} else { return false;}}
compare("mary", "arms");
Make the function return false if the length between words differ and if it finds a character between the words that doesn't match.
// check if two strings are anagrams
var areAnagrams = function(a, b) {
// if length is not the same the words can't be anagrams
if (a.length != b.length) return false;
// make words comparable
a = a.split("").sort().join("");
b = b.split("").sort().join("");
// check if each character match before proceeding
for (var i = 0; i < a.length; i++) {
if ((a.charAt(i)) != (b.charAt(i))) {
return false;
}
}
// all characters match!
return true;
};
It is specially effective when one is iterating through a big dictionary array, as it compares the first letter of each "normalised" word before proceeding to compare the second letter - and so on. If one letter doesn't match, it jumps to the next word, saving a lot of time.
In a dictionary with 1140 words (not all anagrams), the whole check was done 70% faster than if using the method in the currently accepted answer.
an anagram with modern javascript that can be use in nodejs. This will take into consideration empty strings, whitespace and case-sensitivity. Basically takes an array or a single string as input. It relies on sorting the input string and then looping over the list of words and doing the same and then comparing the strings to each other. It's very efficient. A more efficient solution may be to create a trie data structure and then traversing each string in the list. looping over the two words to compare strings is slower than using the built-in string equality check.
The function does not allow the same word as the input to be considered an anagram, as it is not an anagram. ;) useful edge-case.
const input = 'alerting';
const list1 = 'triangle';
const list2 = ['', ' ', 'alerting', 'buster', 'integral', 'relating', 'no', 'fellas', 'triangle', 'chucking'];
const isAnagram = ((input, list) => {
if (typeof list === 'string') {
list = [list];
}
const anagrams = [];
const sortedInput = sortWord(input).toLowerCase();
const inputLength = sortedInput.length;
list.forEach((element, i) => {
if ( inputLength === element.length && input !== element ) {
const sortedElement = sortWord(element).toLowerCase();
if ( sortedInput === sortedElement) {
anagrams.push(element);
}
}
});
return anagrams;
})
const sortWord = ((word) => {
return word.split('').sort().join('');
});
console.log(`anagrams for ${input} are: ${isAnagram(input, list1)}.`);
console.log(`anagrams for ${input} are: ${isAnagram(input, list2)}.`);
Here is a simple algorithm:
1. Remove all unnecessary characters
2. make objects of each character
3. check to see if object length matches and character count matches - then return true
const stripChar = (str) =>
{
return str.replace(/[\W]/g,'').toLowerCase();
}
const charMap = str => {
let MAP = {};
for (let char of stripChar(str)) {
!MAP[char] ? (MAP[char] = 1) : MAP[char]++;
}
return MAP;
};
const anagram = (str1, str2) => {
if(Object.keys(charMap(str1)).length!==Object.keys(charMap(str2)).length) return false;
for(let char in charMap(str1))
{
if(charMap(str1)[char]!==charMap(str2)[char]) return false;
}
return true;
};
console.log(anagram("rail safety","!f%airy tales"));
I think this is quite easy and simple.
function checkAnagrams(str1, str2){
var newstr1 = str1.toLowerCase().split('').sort().join();
var newstr2 = str2.toLowerCase().split('').sort().join();
if(newstr1 == newstr2){
console.log("String is Anagrams");
}
else{
console.log("String is Not Anagrams");
}
}
checkAnagrams("Hello", "lolHe");
checkAnagrams("Indian", "nIndisn");
//The best code so far that checks, white space, non alphabets
//characters
//without sorting
function anagram(stringOne,stringTwo){
var newStringOne = ""
var newStringTwo = ''
for(var i=0; i<stringTwo.length; i++){
if(stringTwo[i]!= ' ' && isNaN(stringTwo[i]) == true){
newStringTwo = newStringTwo+stringTwo[i]
}
}
for(var i=0; i<stringOne.length; i++){
if(newStringTwo.toLowerCase().includes(stringOne[i].toLowerCase())){
newStringOne=newStringOne+stringOne[i].toLowerCase()
}
}
console.log(newStringOne.length, newStringTwo.length)
if(newStringOne.length==newStringTwo.length){
console.log("Anagram is === to TRUE")
}
else{console.log("Anagram is === to FALSE")}
}
anagram('ddffTTh####$', '#dfT9t#D##H$F')
function anagrams(str1,str2){
//spliting string into array
let arr1 = str1.split("");
let arr2 = str2.split("");
//verifying array lengths
if(arr1.length !== arr2.length){
return false;
}
//creating objects
let frqcounter1={};
let frqcounter2 ={};
// looping through array elements and keeping count
for(let val of arr1){
frqcounter1[val] =(frqcounter1[val] || 0) + 1;
}
for(let val of arr2){
frqcounter2[val] =(frqcounter2[val] || 0) + 1;
}
console.log(frqcounter1);
console.log(frqcounter2);
//loop for every key in first object
for(let key in frqcounter1){
//if second object does not contain same frq count
if(frqcounter2[key] !== frqcounter1[key]){
return false;
}
}
return true;
}
anagrams('anagrams','nagramas');
The fastest Algorithm
const isAnagram = (str1, str2) => {
if (str1.length !== str2.length) {
return false
}
const obj = {}
for (let i = 0; i < str1.length; i++) {
const letter = str1[i]
obj[letter] ? obj[letter] += 1 : obj[letter] = 1
}
for (let i = 0; i < str2.length; i++) {
const letter = str2[i]
if (!obj[letter]) {
return false
}
else {
obj[letter] -= 1
}
}
return true
}
console.log(isAnagram('lalalalalalalalala', 'laalallalalalalala'))
console.time('1')
isAnagram('lalalalalalalalala', 'laalallalalalalala') // about 0.050ms
console.timeEnd('1')
const anagram = (strA, strB) => {
const buildAnagram = (str) => {
const charObj = {};
for(let char of str.replace(/[^\w]/g).toLowerCase()) {
charObj[char] = charObj[char] + 1 || 1;
}
return charObj;
};
const strObjAnagramA = buildAnagram(strA);
const strObjAnagramB = buildAnagram(strB);
if(Object.keys(strObjAnagramA).length !== Object.keys(strObjAnagramB).length) {
console.log(strA + ' and ' + strB + ' is not an anagram');
return false;
}
for(let char in strObjAnagramA) {
if(strObjAnagramA[char] !== strObjAnagramB[char]) {
console.log(strA + ' and ' + strB + ' is not an anagram');
return false;
}
}
return true; } //console.log(anagram('Mary','Arms')); - false
Similar approach with filter function
const str1 = 'triangde'
const str2 = 'integral'
const st1 = str1.split('')
const st2 = str2.split('')
const item = st1.filter((v)=>!st2.includes(v))
const result = item.length === 0 ? 'Anagram' : 'Not anagram' + ' Difference - ' + item;
console.log(result)

Categories

Resources