scrimba
Helen Chong's JavaScriptmas 2023 Solutions
Helen Chong's JavaScriptmas 2023 Day 6 solution
Go Pro!Bootcamp

Bootcamp

Study group

Collaborate with peers in your dedicated #study-group channel.

Code reviews

Submit projects for review using the /review command in your #code-reviews channel

Helen Chong's JavaScriptmas 2023 Day 6 solution
AboutCommentsNotes
Helen Chong's JavaScriptmas 2023 Day 6 solution
Expand for more info
index.js
run
preview
console
const people = ["Alice", "Bob", "Carly", "Dan", "Ed", "Ferdinand", "Ginny"]

const secretSantaBtn = document.querySelector('.secret-santa-btn')
const secretSantaList = document.querySelector('.secret-santa ul')

const generateSecretSantaPairs = (arr) => {
// Your code here
const secretSantaPairs = arr.reduce((accumulator, value) => {
return {...accumulator, [value]: ''};
}, {});

const arrayCopy = [...arr]
const shuffleArray = (arr) => arr.sort(() => Math.random() - 0.5)
const shuffledPeople = shuffleArray(arrayCopy)

for (let i = 0; i < arr.length; i++) {
for (let j = 0; j < shuffledPeople.length; j++) {
if (shuffledPeople[j] == arr[i]) {
// Add key:value pairs to the secretSantaPairs object
// Loop back to the start of the shuffledPeople array if index is larger than the array length
secretSantaPairs[arr[i]] = shuffledPeople[(j + 1) % shuffledPeople.length]
}
}
}

// return secretSantaPairs
console.log(secretSantaPairs)

for (const [key, value] of Object.entries(secretSantaPairs)) {
// console.log(`${key}: ${value}`)
secretSantaList.innerHTML += `
<li>${key}: ${value}</li>
`
}
}

// console.log(generateSecretSantaPairs(people))

/**
Example output:
{
Alice: "Dan",
Bob: "Ferdinand",
Carly: "Ed",
Dan: "Alice",
Ed: "Ginny",
Ferdinand: "Bob",
Ginny: "Carly"
}
*/

secretSantaBtn.addEventListener('click', () => {
if (secretSantaList.hasChildNodes()) {
secretSantaList.innerHTML = ''
}
generateSecretSantaPairs(people)
})
Console
/index.html
LIVE