dereknahman
dereknahman

Reputation: 87

Checking JavaScript array equality using forEach

I'm trying to check for array equality using forEach in JavaScript. This criteria is key, and the answer is not on Stack Overflow already.

The tests that are checking equality and expecting true are failing. I have a feeling I'm running into an issue to do with scope. Can someone please walk me through it?

function eql(arr1, arr2) {
  
  arr1.forEach((el) => {
    if (arr1[el] === arr2[el]) {
      return true;
    } 
  })
  return false
}

Here are the test results I want to change:

eql([], [])

Expected: true but got: false

eql(['a', 'b'], ['a', 'b'])

Expected: true but got: false

Upvotes: 0

Views: 395

Answers (2)

Ahmad Suddle
Ahmad Suddle

Reputation: 190

This can be one of the many solutions

function eql(arr1, arr2) {
  let returnStatement = true;

  if (arr1.length !== arr2.length) {
    returnStatement = false;
  } else if (returnStatement) {
    arr1.forEach((el, index) => {
      if (el !== arr2[index]) {
        returnStatement = false;
      }
    });
  }

  return returnStatement;
}

console.log(eql([1, 2, 4], [1, 2, 4]))

Upvotes: 1

Jamiec
Jamiec

Reputation: 136154

There are a number of things wrong with your code

  • forEach doesnt return anything, it just iterates over the items performing some task
  • even if forEach did return something you're not returning the result from your method!
  • el is the element itself, not its index
  • returning true from inside the method passed to forEach does not return from the eql method itself. Your method will always return false.
  • ... but even if that worked, returning true on the first match will not tell you the entire array equals

Your code can be shortened to

function eql(arr1, arr2) {
    return arr1.length == arr2.length && arr1.every( (x,i) => x == arr2[i]);
}

console.log(eql([],[]));
console.log(eql([1,2,3],[1,2,3]));
console.log(eql([1,2,3],[1,2,2]));
console.log(eql([1,2,3],[1,2,3,4]));

Upvotes: 1

Related Questions