0

I need help, I have two array like this

let A = ['a', 'b', 'c']
let B = ['a', 'b', 'c']

and I try this but not work

if(A === B) {
  console.log('EQUAL')
} else {
  console.log('NOT EQUAL')
}

how to check if they are equal in vue? how to implement it?

  • Does this answer your question? [How to compare arrays in JavaScript?](https://stackoverflow.com/questions/7837456/how-to-compare-arrays-in-javascript) – Sysix Oct 21 '21 at 09:46

2 Answers2

0

You can create a function which checks if they are equal by doing the following:

let A = ['a', 'b', 'c']
let B = ['a', 'b', 'c']
let C = ['a', 'b', 'd']
    
function isEqual(arr1, arr2) {
  for (let i = 0; i < arr2.length; i++) {
    if (arr1[i] !== arr2[i]) return false;
  }
  // return true if above checks are passed
  return true;
}
    
console.log(isEqual(A, B))
console.log(isEqual(A, C))

EDIT: You should add a if check to avoid nullpointerexceptions

function isEqual(arr1, arr2) {
   if (arr1.length !== arr2.length) return false;
}
Markiesch
  • 721
  • 3
  • 11
0

An easier way would be using JSON.stringify (ie)

if(JSON.stringify(arr1) === JSON.stringify(arr2))

Using the above you can compare multidimensional array of n level and no for-loops are needed

Amaarockz
  • 4,348
  • 2
  • 9
  • 27