skip to Main Content

Are there any improvements that can be made on the following to check the equality of two arrays in javascript?

"use strict"
function main(arr1, arr2) {
    if (arr1.length !== arr2.length) {
        return false;
    }
    for (let i = 0; i < arr1.length; i++) {
        if (arr1[i] !== arr2[i]) {
            return false
        }
    }
    return true;
}
const tests = [
  [[1,2],[1,2]],
  [[1],[1,2]],
  [[1,2],[1]],
  [[1,2],[3,4]],
  [[],[]]
]
for (const [arr1, arr2] of tests) {
  let res = main(arr1, arr2);
  console.log(arr1, arr2, res);
}

2

Answers


  1. Not sure this is an improvement, but you could make it shorter:

    "use strict"
    
    function main(arr1, arr2) {
        return (
          arr1.length === arr2.length
          && arr1.every((v, i) => arr2[i] === v)
        );
    }
    
    const tests = [
      [[1,2],[1,2]],
      [[1],[1,2]],
      [[1,2],[1]],
      [[1,2],[3,4]],
      [[],[]]
    ]
    for (const [arr1, arr2] of tests) {
      let res = main(arr1, arr2);
      console.log(arr1, arr2, res);
    }
    Login or Signup to reply.
  2. There is no further improvement in terms of the algorithm used to check array equality, AFAIK.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search