- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Check if values of two arrays are the same/equal in JavaScript
We have two arrays of numbers, let’s say −
[2, 4, 6, 7, 1] [4, 1, 7, 6, 2]
Assume, we have to write a function that returns a boolean based on the fact whether or not they contain the same elements irrespective of their order.
For example −
[2, 4, 6, 7, 1] and [4, 1, 7, 6, 2] should yield true because they have the same elements but ordered differently.
Now, let’s write the code for this function −
Example
const first = [2, 4, 6, 7, 1]; const second = [4, 1, 7, 6, 2]; const areEqual = (first, second) => { if(first.length !== second.length){ return false; }; for(let i = 0; i < first.length; i++){ if(!second.includes(first[i])){ return false; }; }; return true; }; console.log(areEqual(first, second));
Output
The output in the console will be −
true
Advertisements