JavaScript function to check equality of two arrays

javascript compare two arrays of objects for matches
javascript compare two arrays for matches
javascript check if two arrays have same elements
comparing two arrays in javascript returning differences
compare two arrays javascript es6
lodash compare arrays
javascript difference between two arrays of objects
how to compare elements in an array javascript

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!

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

How to check if two arrays are equal with JavaScript?, To check for equality, we first need to make sure the arrays are the same length. If not, they're not equal and we can return false . var arraysMatch = function (arr1, arr2) { // Check if the arrays are the same length if (arr1. length !== With that in mind, here's 3 definitions of equality for arrays and how to check them. Same Length, Each Value Equal. One approach for comparing a and b is checking if each value of a is strictly equal to the corresponding value of b. This works well if all the elements of the arrays are primitives as opposed to objects.

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

How to check if two arrays are equal with vanilla JS, JavaScript provides a function JSON.stringify() in order to convert an object or array into JSON string. By converting into JSON string we can� Given two given arrays of equal length, the task is to find if given arrays are equal or not. Two arrays are said to be equal if both of them contain same set of elements, arrangements (or permutation) of elements may be different though. Note : If there are repetitions, then counts of repeated elements must also be same for two array to be equal.

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;
  } 
} 

How to compare two arrays in JavaScript?, Comparison of arrays by using forEach method. Now we are writing the compare function it helps us to compare above two arrays. Let's start� There is no easy way to do this. I needed this as well, but wanted a function that can take any two variables and test for equality. That includes non-object values, objects, arrays and any level of nesting.

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

Comparison of Two arrays Using JavaScript, In vanilla JavaScript, unfortunately, there is no direct method available to compare two arrays to check if they are equal. If you Google this, you'll� var array3 = array1 === array2 That will compare whether array1 and array2 are the same array object in memory, which is not what you want. In order to do what you want, you’ll need to check whether the two arrays have the same length, and that each member in each index is identical.

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

How to compare two arrays in JavaScript, In this post, we will see how to compare arrays of any depth in JavaScript. Two arrays are said to be equal if they have same elements in the same order. For converting the array to a JSON string, you can use the JSON.stringify() method. Problem Description. How to check if two arrays are equal or not? Solution. Following example shows how to use equals method of Arrays to check if two arrays are equal or not.

Compare Arrays in JavaScript, JavaScript exercises, practice and solution : Write a JavaScript function to find the difference of two arrays. In Javascript, to compare two arrays we need to check that the length of both arrays should be same, the objects present in it are of the same type and each item in one array is equal to the counterpart in another array.

JavaScript array: Find the difference of two arrays, Get code examples like "how to compare elements of two arrays in javascript" instantly right from your google search results with the Grepper� If you are using lodash and don't want to modify either array, you can use the function _.xor(). It compares the two arrays as sets and returns the set that contains their difference. If the length of this difference is zero, the two arrays are essentially equal:

how to compare elements of two arrays in javascript Code Example, Javascript: Comparing two arrays for equality. Don't Google this, you will lose all will to live. Instead use Object#isEqual from Lodash or Underscore.js: Copy. _.

Comments
  • 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.
  • Does this answer your question? How to compare arrays in JavaScript?
  • As I said in the original question, I'm required to use Array.forEach.
  • @will-t-harris What is that, some kind of homework question? There is no reason why Array.forEach must be used when simpler methods of comparison like Array.prototype.every does the same thing.
  • @will-t-harris I have added the way for forEach
  • Thank you, I knew I was missing something obvious with my solution. I appreciate it!