0

Having some trouble understanding why my numbers aren't giving me the correct equality in javascript.

I inserted a vector of numbers into an array in javascript...

const seen = [ 
                [0,1] 
              ];
console.log(contains(seen, [0,1]));

And then tried to do a simple comparison

    const contains = function(arr, coordinate){
        arr.forEach(element => {
            if(element[0] == coordinate[0] && element[1] == coordinate[1]){
         

       return true;
        }
    })

    return false;
}

Im expecting my contains function to return true. Element is [0,1] and the coordinate im comparing to is also [0,1], yet when I try to compare with the following:

element[0] == coordinate[0] && element[1] == coordinate[1]

It ultimately returns false.

Full code:

const contains = function(arr, coordinate) {
  arr.forEach(element => {
    if (element[0] === coordinate[0] && element[1] === coordinate[1]) {
      return true;
    }
  })

  return false;
}

const seen = [
  [0, 1]
];
console.log(contains(seen, [0, 1]))
Barmar
  • 741,623
  • 53
  • 500
  • 612
Kevin Price
  • 389
  • 2
  • 5
  • 11

1 Answers1

2

You need to change the forEach to a normal for. Right now return is returning only from the lambda.

const contains = function(arr, coordinate) {
    for (const element of arr) {
        if(element[0] == coordinate[0] && element[1] == coordinate[1]) {
            return true;
        }
    }
    return false;
}
Ceribe
  • 136
  • 2
  • 3
  • 9