-1

I'm tasked with writing a function that takes two 1-dimensional arrays of simple values (no objects, etc), and returns true only if they are equal. The function also must use the Array.forEach() method.

So far, I've tried

function eql(arr1, arr2) {
  if(arr1.length !== arr2.length){return false}
  arr1.forEach((element, index) => {
    if(element !== arr2[index]){
      return false
    }
  })
  return true
}

And this gets most of my tests to pass, although the cases that are still failing are

eql([1], [2])
eql(['a', 'b'], ['a', 'c'])
eql([1], ['1'])

All three of these cases are returning true, when I'm expecting false. Thanks in advance for any help, I've been trying to sort through the logic on my own and feel like I've hit a wall!

  • You’re returning true in the end so of course all invocations will return true. Returning false inside of a foreach loop doesn’t do what you think it does. – Terry Jan 07 '20 at 17:11
  • 1
    Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Anurag Srivastava Jan 07 '20 at 17:13

5 Answers5

6

Using return inside forEach is meaningless. You should use every()

function eql(arr1, arr2) {
  if(arr1.length !== arr2.length){return false}
  return arr1.every((e, i) => e === arr2[i]);
}
console.log(eql(['a', 'b'], ['a', 'c']))

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

If you really want to use forEach() then use need to create a local variable.

function eql(arr1, arr2) {
  if(arr1.length !== arr2.length){return false}
  let res = true;
  arr1.forEach((element, index) => {
    if(element !== arr2[index]){
      res = false
    }
  })
  return res;
}

console.log(eql(['a', 'b'], ['a', 'c']))
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
1

Setup a default isEqual variable. If it is not equal it changes and print that outcome. This is because forEach just iterates over the items. You need to do the logic inside the loop.

function eql(arr1, arr2) {
  let isEqual = true;
  if(arr1.length !== arr2.length){isEqual = false}
  arr1.forEach((element, index) => {
    if(element !== arr2[index]){
      isEqual = false;
    }
  })
  console.log(isEqual);
}

eql([1], [2])
eql(['a', 'b'], ['a', 'c'])
eql([1], ['1'])

But really: Use JSON.stringify for simple cases like this:

function eql(arr1, arr2) {
  console.log(JSON.stringify(arr1) === JSON.stringify(arr2));
}

eql([1], [2])
eql(['a', 'b'], ['a', 'c'])
eql([1], ['1'])
eql([1], [1])
Mouser
  • 13,132
  • 3
  • 28
  • 54
0

This version might be a little more clear to some people:

function arraysAreEqual(a, b) 
{ 
  if(a.length!=b.length) 
   return False;   // can't be equal if not the same length
  else
  { 
   for(var i=0;i<a.length;i++) {
     if(a[i]!=b[i]) return False;   // quit on first mismatch
   }
   return True;
  } 
} 
Mike Robinson
  • 8,490
  • 5
  • 28
  • 41
0

If you say the arrays are equal regardless of the position of elements in the array like for example if eql([1,2], [2,1]) should return true; you should either sort the array first and use index based comparison like the answers given above or else check if one element exists in the other array without the need for sorting

function eql(arr1, arr2) {
  if(arr1 === arr2) //in case primitive values are passed to the function or both arrays happen to have the same reference.
    return true;  
  
  if(arr1.length !== arr2.length)
    return false;
  
  let equal = true;
  arr1.forEach(a => {
    if(!arr2.includes(a)) { //assuming the order doesn't matter
      equal = false;
      return;
    }
  })
  
  return equal;
}
console.log(eql(['1'], [1]))
console.log(eql([1,2], [2,1]))
Addis
  • 2,480
  • 2
  • 13
  • 21
0

From Mozilla Developer Network

So you try the same with other methods of iteration like this:

function eql(arr1,arr2) {
  if(arr1.length!==arr2.length) { return false }
  return arr1.every((element,index)=>{
    if(element===arr2[index]){
      return true
    } else {
      return false
    }
  });
  
}

console.log(eql([1], ['1']));
console.log(eql(['a', 'b'], ['a', 'c']));
console.log(eql([1], ['1']));
Kumar Gaurav
  • 738
  • 4
  • 11