Home > front end >  check 2 arrays if the result is equal in vue
check 2 arrays if the result is equal in vue

Time:10-21

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?

CodePudding user response:

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))
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

EDIT: You should add a if check to avoid nullpointerexceptions

function isEqual(arr1, arr2) {
   if (arr1.length !== arr2.length) return false;
}

CodePudding user response:

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

  • Related