Last active
September 4, 2021 07:17
-
-
Save cyberbarbie/cdeaa2a6586b488584398b69c0338605 to your computer and use it in GitHub Desktop.
Coding Challenge: Find Common Values in 2 Arrays
This file contains 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
let friendsList1 = ["Monique", "Joe", "Levar", "Tylere", "Leann"] | |
let friendsList2 = ["Monique", "Joe", "Tyler", "Koa", "Leann"] | |
let commonFriends = [] | |
// loop through 2 lists and add common values to empty array | |
let friendsMatch = (arr1, arr2) => { | |
for (friend1 = 0; friend1 < arr1.length; friend1++){ | |
for (friend2 = 0; friend2 < arr2.length; friend2++){ | |
// if there are common items, add to empty array | |
if (arr1[friend1] === arr2[friend2]){ | |
commonFriends.push(arr1[friend1]) | |
} | |
} | |
} //convert an array of duplicate values to a Set to remove duplicates and then convert it back to an array | |
let uniqueFriends = [...new Set(commonFriends)] | |
return uniqueFriends | |
} | |
// save common value result from 2 arrays into a variable | |
const commonValueRes = friendsMatch(friendsList1, friendsList2) | |
// display results and handle event when there are no common values found | |
const displayResults = commonFriendValue => { | |
commonFriendValue.length > 0 ? console.log(`You have ${commonFriendValue.length} friends in common. They are: ${commonFriendValue.join(", ")}`) : console.log("You have no friends in common.") | |
} | |
// call the function and pass in result from prev func | |
displayResults(commonValueRes) | |
// print: You have 3 friends in common. They are: Monique, Joe, Leann |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment