scrimba
Note at 1:57
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

Note at 1:57
AboutCommentsNotes
Note at 1:57
Expand for more info
index.js
run
preview
console
const people = ["Alice", "Bob", "Carly", "Dan", "Ed", "Ferdinand", "Ginny"]

function generateSecretSantaPairs(arr) {
// let pairs = {};
// let copy = [...arr];

// for(let i = 0; i < arr.length; i++) {
// let person = arr[i];
// let index;
// if(copy.length === 1) {
// pairs[person] = copy[0];
// pairs[copy[0]] = person;
// break;
// }

// do {
// index = Math.floor(Math.random() * copy.length);
// } while(copy[index] === person && copy.length > 1)

// pairs[person] = copy[index];
// copy.splice(index, 1);
// }
// console.log(pairs)
// return pairs;

let pairs = {};
let copy = [...arr];

for(let i = 0; i < arr.length; i++) {
let person = arr[i];
let index;
if(copy.length === 1) {
pairs[person] = copy[0];
pairs[copy[0]] = person;
break;
}

do {
index = Math.floor(Math.random() * copy.length);
} while(copy[index] === person || Object.values(pairs).includes(copy[index]) && copy.length > 1)

pairs[person] = copy[index];
copy.splice(index, 1);
}
console.log(pairs)
return pairs;
}

generateSecretSantaPairs(people);

/**
Example output:
{
Alice: "Dan",
Bob: "Ferdinand",
Carly: "Ed",
Dan: "Alice",
Ed: "Ginny",
Ferdinand: "Bob",
Ginny: "Carly"
}
*/
Console
{Alice:
"Ginny"
, Bob:
"Dan"
, Carly:
"Ferdinand"
, Dan:
"Alice"
, Ed:
"Ginny"
, Ferdinand:
"Carly"
, Ginny:
"Ed"
}
,
/index.html
LIVE