Last active
July 17, 2022 15:09
-
-
Save ahamed/59b940ef6c3f20c4217936e3f897c3b7 to your computer and use it in GitHub Desktop.
Check if two arrays are same i.e. same elements but in different order.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| const arr1 = [1, 2, 3, 4, 6, 5, 2]; | |
| const arr2 = [2, 3, 1, 4, 2, 5, 6]; | |
| const isSameArray = (arr1, arr2) => { | |
| if (arr1.length !== arr2.length) { | |
| return false; | |
| } | |
| // Create object like {1: 1, 2: 2, 3: 1 ...} , the number of frequency of an element in the array. | |
| const obj1 = arr1.reduce((a, c) => { | |
| a[c] ||= 0; | |
| a[c]++; | |
| return a; | |
| }, {}); | |
| // Same for the arr2 | |
| const obj2 = arr2.reduce((a, c) => { | |
| a[c] ||= 0; | |
| a[c]++; | |
| return a; | |
| }, {}); | |
| // Now traverse through the obj1 and check if the element count is same or not. | |
| // If not same then imediately return false. | |
| for (const key in obj1) { | |
| if (obj1[key] !== obj2[key]) { | |
| return false; | |
| } | |
| } | |
| return true; | |
| } | |
| console.log(isSameArray(arr1, arr2)); // true |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment