Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Shallow array equals in javascript

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

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading