简体   繁体   中英

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

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]));

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]))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM