This question already has answers here:
How to check if two arrays are equal with JavaScript? [duplicate]
(16 answers)
Closed 3 years ago.
Hi this is probably an easy question. So I want to make a basic anagram function in Javascript.
The following snippet does not work
anagrams = (phraseOne, phraseTwo) => {
if (phraseOne.split("").sort() === phraseTwo.split("").sort()) {
return true
} else {
return false
}
}
However this does work
anagrams = (phraseOne, phraseTwo) => {
if (phraseOne.split("").sort().join("") === phraseTwo.split("").sort().join("")) {
return true
} else {
return false
}
}
Why? The arrays are identical before you join("") them
That's because strings are compared by value and arrays are compared by reference in JS. You can find out more about comparison here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness
Related
This question already has answers here:
Closure in JavaScript - whats wrong?
(7 answers)
"add" function that works with different combinations of chaining/arguments
(4 answers)
Puzzle: JS Function that returns itself until there are no arguments
(5 answers)
Variadic curried sum function
(19 answers)
Closed 1 year ago.
I just started learning closures in JavaScript and I'm trying to understand a basic problem.
For example, I'm trying to implement the sum method: sum(1)(4)(5)
const sum = (a) => {
return (b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
}
When I call: console.log(sum(1)(4)(5)()) it works perfect and return 10. However, if I call console.log(sum(1)(4)(5)), it returns [Function (anonymous)]. Why?
Thanks
Every time you call your function like:
sum(1)(10)
you are returning the inner function:
(b) => {
if(typeof b === 'number')
return sum(a+b)
return a;
}
Because type of b === 'number' and you are returning sum(a+b) that calls
again the function sum and returns again the inner function. Thats why when you finally put the last parenthesis like:
sum(1)(10)()
The inner function will execute and type of b in this case is different from number and will return 'a' that already contains the sum of the values.
This question already has answers here:
How can I check if an object is an array? [duplicate]
(51 answers)
Closed 3 years ago.
I have the following variables which are arrays:
const gumBrands = ['orbit', 'trident', 'chiclet', 'strident'];
const mintBrands = ['altoids', 'certs', 'breath savers', 'tic tac'];
Below I have the following function that uses the variables as input arguments:
function shallowCopy (arrOne, arrTwo) {
if (arrOne.constructor === 'Array'){
return [...arrOne, ...arrTwo];
}
else {
console.log('test this');
}
}
shallowCopy(gumBrands, mintBrands)
I am expecting my code to return:
[ 'orbit',
'trident',
'chiclet',
'strident',
'altoids',
'certs',
'breath savers',
'tic tac' ]
Instead the code runs my else statement and returns: test this
What am I doing wrong?
.constructor does not contain the string "Array" but a reference to the global Array object.
Note that arrays can be subclassed, and their .constructor is different. You might want to consider to check with instanceof Array.
This question already has answers here:
What does `return` keyword mean inside `forEach` function? [duplicate]
(2 answers)
Short circuit Array.forEach like calling break
(30 answers)
Closed 4 years ago.
function checkMagazine(magazine, note) {
var map = new Map();
var noteAr = note.split(" ");
var magazineAr = magazine.split(" ")
noteAr.forEach((note) => {
if (map.has(note)) {
map.set(note, map.get(note) + 1)
} else {
map.set(note)
}
});
magazineAr.forEach((word) => {
if (!map.has(word)) {
return "No"
}
});
return "Yes"
}
I'm checking to see if each word of a note is contained in the magazine by first hashing the values of the note and checking them in magazineAr. If the note word does not exist in the hash, then I am return "NOing. However, I keep getting a return "YES" in console.
I've watched it in debugger mode and I see it enter the statement where it hits 'return No' but then it just keeps on going with the forEach loop. I've even tried return false but same thing.
A forEach callback ignores the value that's returned - no matter what it is, every item in the array will be called with the forEach. For what you're trying to do, you should probably use every instead, which checks whether all items in the array fulfill the condition:
const hasEveryWord = magazineAr.every(word => map.has(word));
return hasEveryWord
? "Yes"
: "No";
This question already has answers here:
Is there a “not in” operator in JavaScript for checking object properties?
(6 answers)
Closed 5 years ago.
I'm trying to return an object with each letter from a string as a key, and each key's value being the amount of times that letter appears.
The if statement doesn't seem to execute, I think it's a problem with the not operator because I can get it to execute if I remove it and put the letter in the object so that it evaluates to true.
function multipleLetterCount(str){
var countObj = {};
for(var i = 0; i < str.length; i++){
//Why won't this if statement run???
if(!str[i] in countObj){
countObj[str[i]] = 1;
} else {
countObj[str[i]]++;
}
}
return countObj;
}
multipleLetterCount("aaa")
It returns {a: NaN}
You need to wrap your condition with the negation operator (!)
if(!(str[i] in countObj))
Or even better, invert your condition:
if (str[i] in countObj) {
countObj[str[i]]++;
} else {
countObj[str[i]] = 1;
}
This question already has answers here:
What is the !! (not not) operator in JavaScript?
(42 answers)
Closed 5 years ago.
i try to reading code of pandajs game engine and according to this code from github :
playMusic: function(name, loop) {
var volume = this.musicMuted ? 0 : this.musicVolume;
if (typeof loop === 'undefined') loop = true;
if (this.currentMusic) this._stop(this.currentMusic);
this.currentMusic = this._play(name, !!loop, volume);
this.currentMusicName = name;
return !!this.currentMusic;
}
and it's return !!this.currentMusic i try to figure it out but i cant understand why he use it. for example this code :
function a(arg){
console.log(!!arg);
}
a(true)
a(false)
if i pass true it's print true and if i pass false it's print false , so why not just return this.currentMusic instead of !!this.currentMusic or in my example just console.log(arg) instead of console.log(!!arg)
it coerces the object to boolean, if it was null, undefined etc it would be false else true
let x = null;
let y = 1;
console.log(!!x);
console.log(!!y);