An Interest In:
Web News this Week
- March 19, 2024
- March 18, 2024
- March 17, 2024
- March 16, 2024
- March 15, 2024
- March 14, 2024
- March 13, 2024
July 23, 2021 06:10 am GMT
Original Link: https://dev.to/rthefounding/comparing-two-different-arrays-209f
Comparing Two Different Arrays
- Second we will simply compare two arrays and return a new array with any items only found in one of the two given arrays, but not both. Remember the keyword "not both".
- Problem Below:
function arrays(arr1, arr2) {}arrays([1, 2, 4, 5], [1, 2, 3, 4, 5]);
Answer:
function arrays(arr1, arr2) { let merge = arr1.concat(arr2); return merge.filter(function(num) { // <--- num are all the numbers in merge. [1, 2, 4, 5, 1, 2, 3, 4, 5] if (arr1.indexOf(num) === -1 || arr2.indexOf(num) === -1) { return num; } })}console.log(diffArray([1, 2, 4, 5], [1, 2, 3, 4, 5])); // will display [3]
- We're just checking the two arrays and return a new array that contains only the items that are not in either of the original arrays. In this case 3.
- What we did was merge the list to make it easy to compare and used filter to get the new array in which you will need to create a callback function.
Original Link: https://dev.to/rthefounding/comparing-two-different-arrays-209f
Share this article:
Tweet
View Full Article
Dev To
An online community for sharing and discovering great ideas, having debates, and making friendsMore About this Source Visit Dev To