Skip to content

Instantly share code, notes, and snippets.

@cyberbarbie
Last active September 4, 2021 07:17
Show Gist options
  • Save cyberbarbie/cdeaa2a6586b488584398b69c0338605 to your computer and use it in GitHub Desktop.
Save cyberbarbie/cdeaa2a6586b488584398b69c0338605 to your computer and use it in GitHub Desktop.
Coding Challenge: Find Common Values in 2 Arrays
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