Last active
September 2, 2021 06:07
-
-
Save cyberbarbie/f6ecf6f5a08f99768e022398f60e58f1 to your computer and use it in GitHub Desktop.
Find occurrences in 2 arrays & return an array of unique values
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
// Find & return common occurences in 2 arrays & return the unique values in a new array; if there are no common occurences between the 2 arrays, provide a response | |
let arr1 = ["Leila", "Fry", "Leila", "Bender"] | |
let arr2 = ["Leila", "Bender", "Fry", "Bailey"] | |
let commonFriends = [] | |
// Iterate through 2 arrays & adds common values to empty list | |
findTheMutuals = (arr1, arr2) => { | |
for (let arr1Index = 0; arr1Index < arr1.length; arr1Index++){ | |
for (let arr2Index = 0; arr2Index < arr2.length; arr2Index++){ | |
if ( arr1[arr1Index] === arr2[arr2Index]){ | |
commonFriends.push(arr1[arr1Index]) | |
} | |
} | |
} | |
// conditional runs if there are matching values from both arrays | |
if (commonFriends.length > 0){ | |
// create new array of unique values | |
commonFriends = Array.from(new Set(commonFriends)) | |
// sort array alphabetically & add space and comma between values | |
let formattedArr = commonFriends.sort().join(", ") | |
// display the length of values in common | |
console.log(`You have ${commonFriends.length} friends in common. `) | |
// display the common values | |
console.log(`Mutual Friends: ${formattedArr}`) | |
} else { | |
// runs if there are NO mutual values | |
console.log("You have no mutual friends") | |
} | |
} | |
// call function with 2 arrays | |
findTheMutuals(arr1, arr2) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment