JS Coding Questions Logo
JS Coding Questions
#287💼 Interview💻 Code

How do you compare scalar arrays

Advertisement

728x90

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
1const arrayFirst = [1, 2, 3, 4, 5];
2
3const arraySecond = [1, 2, 3, 4, 5];
4
5console.log(
6  arrayFirst.length === arraySecond.length &&
7  arrayFirst.every((value, index) => value === arraySecond[index])
8); // true

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

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

Advertisement

Responsive Ad
🎯 Practice NowRelated Challenge

JavaScript Coding Exercise 31

Test your knowledge with this interactive coding challenge.

Start Coding

Advertisement

728x90
287of476