1

I'm struggling a bit with higher-order functions. I want to compare two arrays to see if all the values of one array are part of another array. In that case I want to return true, otherwise false.

My code:


let arrayA = [4,5,6,7]
let arrayB = [4,5,6,7,8];

let result = arrayA.forEach(number => {

  if (!arrayB.includes(number)){
    return false
 }

  else {
    return true
 }

})

console.log(result)  //=> undefined

Thanks for reading or even helping a beginner out!

Jenny
  • 494
  • 1
  • 4
  • 16
  • 1
    `forEach` doesn't return anything. You want `let result = arrayA.every(number => arrayB.includes(number))` – Niet the Dark Absol Sep 02 '20 at 09:14
  • you are right, thank you! – Jenny Sep 02 '20 at 09:15
  • 1
    Your mistake is using `.forEch()` instead of `.every()` or `.some()`. Note also this style issue with your code: the `if else` are overkill. `!arrayB.includes(number)` is a boolean value: it is true or false. You can return that value directly, rather than explicitly writing `return true` and `return false` inside an `if else` block. – Stef Sep 02 '20 at 09:17

1 Answers1

1

.forEach is not suitable here (it does not return). Use .some and .indexOf as follows:

let arrayA = [4,5,6,7]
let arrayB = [4,5,6,7,8];

let result = !arrayA.some(val => arrayB.indexOf(val) === -1);

console.log(result)
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
  • This is basically the negation of what I posted in my comment - instead of testing if every element of A is in B, you are testing is there is not an element of A that is not in B. Same result, just a bit weird :D – Niet the Dark Absol Sep 02 '20 at 09:16