So I am trying to understanding the every method.
I wrote the following and it keeps bringing back “false,” but I believe it should be “true.”
let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
let result = array.every((element, i, arr) => element < arr[i + 1])
console.log(result)
I’m assuming I’m doing something super stupid. Just wondering what it is?
Thanks for your help.
Edit: Thank everyone that took the time to reply. I appreciate it!
10 is not less than NaN. When i is 9, arr[i + 1]
is undefined, which is treated as NaN when comparing to a number using <
Array.every() only returns true if every item in the array returns true else it returns false
let arrayOfNumbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] //
const isLessThanFive = (i) => i < 5 // returns type boolean
let boolArray = arrayOfNumbers.map( isLessThanFive ) // returns array with 4 true and 6 false
let isTrueForAll = arrayOfNumbers.every( isLessThanFive ) // uses each item in array as a function argument
console.log(isTrueForAll) // returns false because only 4 items return true
maybe you wanted to use map
? forEach
just return undefined
yup youre right
map
creates a new array
forEach
only executes function on each item. doesnt return new array
i honestly thought they were basically the same