Skip to content

Instantly share code, notes, and snippets.

@juanmaguitar
Last active September 21, 2017 11:25
Show Gist options
  • Save juanmaguitar/d055e0ca39b4f3f7b5c17fff8c1b2cb3 to your computer and use it in GitHub Desktop.
Save juanmaguitar/d055e0ca39b4f3f7b5c17fff8c1b2cb3 to your computer and use it in GitHub Desktop.
shuffle and group
function shuffleAndGroup (students, sizeGroups = 2) {
var shuffled = students.reduce( (acc, item, i, array) => {
var random = Math.floor(Math.random() * array.length);
array[i] = array.splice(random,1,item)[0]
return array
},[])
var grouped = shuffled.reduce((acc, current, index, array) => {
if (index % sizeGroups) {
acc[acc.length - 1].push(current) // add elements to the group
} else {
acc.push([current]) // new group
}
return acc
}, [])
return grouped // return an array of arrays (pairs)
}
var students = ['Emilio', 'Jose Manuel', 'Abel', 'Jese', 'Oscar', 'Nacho', 'Pol', 'Joan Marc', 'Francesc', 'Toni', 'Eva', 'Gemma']
shuffleAndGroup(students, 2)
.forEach((group, i) => {
console.log('----------------')
console.log(`GROUP ${i + 1}`)
group.forEach(student => console.log(student))
})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment