3

How do I check for equality between the elements of two arrays without using external libraries (and preferably using ES5)?

I want to check for equality between them without caring about the order of the elements. So the two arrays [1,2,3] and [2,3,1] are equal in my situation.

I guess I should write a function

function isEqual(arr1, arr2) {
  arr1.forEach(el => {
    if (arr2.indexOf(el) === -1) {
      return false;
    }
  });

  arr2.forEach(el => {
    if (arr1.indexOf(el) === -1) {
      return false;
    }
  });

  return true;
}
Jamgreen
  • 10,329
  • 29
  • 113
  • 224

2 Answers2

3

You can use JSON.stringify and Array#sort methods. Sort both the arrays ang compare them after converting to JSON string.

function isEqual(arr1, arr2) {
  return JSON.stringify(arr1.sort()) === JSON.stringify(arr2.sort());
}

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

Or instead of JSON.stringify you can also use Array#join method( Suggested by @JonCarter ) which makes it little more simple.

function isEqual(arr1, arr2) {
  return arr1.sort().join() === arr2.sort().join();
}

console.log(isEqual([1, 2, 3], [2, 3, 1]));
console.log(isEqual([1, 2, 3], [2, 4, 1]));
console.log(isEqual([1, 2, 3, 3], [2, 3, 1]));
console.log(isEqual([1, 2, 3, 3], [2, 4, 1, 1]));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
0

You could use Array#every to assert the values are equal. This is very rudimentary though as uses a strict equality check which has its limitations. But this shows the rough framework for a iterating over the array.

NOTE: Since arrays are index based lists it is assumed that for them to be equal they would need to have equal values at the same index.

var arr1 = [1,2,3,4];
var arr2 = [1,2,3,4];
var arr3 = [1,2,4];
var arr4 = [1,2,2,4];

function isArrEql(a1, a2) {
  return a1.length === a2.length && a1.every(function(v, i) {
    return v === a2[i];
  });
}

console.log('arr1, arr2: ', isArrEql(arr1, arr2));
console.log('arr1, arr2: ', isArrEql(arr1, arr3));
console.log('arr1, arr2: ', isArrEql(arr1, arr4));
Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
Jason Cust
  • 10,743
  • 2
  • 33
  • 45
  • But is `a1.every((v, i) => v === a2[i])` the same as `a2.every((v, i) => v === a1[i])`? Don't I have to check both ways? – Jamgreen Sep 16 '16 at 05:06
  • @Jamgreen That is what the length check is for. If both arrays are the same length then iterating over one and matching the corresponding value from the other array would have the same result. – Jason Cust Sep 23 '16 at 15:36