InterviewHubPRO
Section Overview
Q291

Question 291 of 521

Part 5: ES6+ Modern Syntax, Classes, Modules & Destructuring (254 - 328)

56%
JavaScript Internals (521 Qs)•Part 5: ES6+ Modern Syntax, Classes, Modules & Destructuring (254 - 328)

How do you compare scalar arrays

You can use length and every method of arrays to compare two scalars (compared directly using ===) arrays. The combination of these expressions can give the expected result,

javascript
  const arrayFirst = [1, 2, 3, 4, 5];
  const arraySecond = [1, 2, 3, 4, 5];
  console.log(
    arrayFirst.length === arraySecond.length &&
      arrayFirst.every((value, index) => value === arraySecond[index])
  ); // true

If you would like to compare arrays irrespective of order then you should sort them before,

javascript
  const arrayFirst = [2, 3, 1, 4, 5];
  const arraySecond = [1, 2, 3, 4, 5];
  console.log(
    arrayFirst.length === arraySecond.length &&
      arrayFirst
        .sort()
        .every((value, index) => value === arraySecond[index])
  ); //true