r/learnjavascript • u/SadBoi23xx • Jan 18 '22
Im having a bit of difficulty with the some and every exercise its says to define a function called allEvens that accepts a single array of numbers.if the array contains evenNumbers return true otherwise return false.I understand what The methods just having a bit of trouble with the syntax
1
u/sharar_rs Jan 18 '22
Which bit of the syntax do you have trouble with ?
1
u/SadBoi23xx Jan 18 '22
Inside of the some or every method everytime I use the method I use an arrow function but the exercise tells me that the function should call some or every but I do call some or every inside of the function
1
u/johnnyblaze9875 Jan 18 '22
Have you tried it with a for loop? Or you have to use methods? It would be good to start with loops so you can understand what is happening on every iteration. You could also use filter and length! Lmk if you need any further elaboration. A lot of the methods are fancy loops under the hood.
3
u/ninjasoards Jan 18 '22
Simplest way:function allEvens(arr) {return arr.every(val => val % 2 === 0)}
1
u/CatsPawmer Jan 18 '22
Function allEvens(numArr) { return numArr.every(num => num % 2 === 0) }
If every number inside the numArr is an even number, you should get back a truthy value. I’m not sure if this is what you need but this is how I would do it.
I know you said you didn’t really have trouble with the methods, but if it helps I tend to view array.prototype.some() as “any” and array.prototype.every as “all”
1
u/bryku helpful Jan 18 '22
It is impossible to read the image, but if I'm understanding it correctly, you want to return true if all the numbers are even.
There are a few ways of doing it, so I will show you how it sort of works and the shortened version.
function allEven(array){
let evenCounter = 0;
for(let i = 0; i < array.length; i++){
if(array[i] % 2 == 0){
evenCounter++;
}
}
if(evenCounter == array.length){
return true
}else{
return false
}
}
allEven([2,4,6,8]); // true
allEven([1,4,6]); // falseA shorter way is to use every. If every condition is true, it will return true.
function allEven(array){
return array.every((v)=>{
if(v % 2 === 0){
return true
}else{
return false
}
});
}
allEven([2,4,6,8]); // true
allEven([1,4,6]); // falseYou can continue to shorten it, but it works the same.
function allEven(array){
return array.every(num => num % 2 === 0)
}
allEven([2,4,6,8]); // true
allEven([1,4,6]); // false1
1
Jan 07 '23 edited Jan 07 '23
I know there's been some time but I want to help other too.
This code can be written using arrow functions like so:
Look just after you try it yourself! You can do it.
const allEvens = nums => nums.every(n => n % 2 === 0);
0
2
u/grantrules Jan 18 '22
Can you explain what you're doing in your code? For example, what is the point of the array named
array?