JS Shuffle

Write a function which implements shuffle

by Gustavo

JavaScript

/* First solution that came to my mind. Only works for arrays. */

const shuffle = function(arr) {
  let shuffled = [];
  let buffer = [...arr];
  while (buffer.length) {
    let rand = Math.floor(Math.random() * (Math.floor(buffer.length - 1) + 1));
    shuffled.push(buffer.splice(rand,1)[0]);
  }
  return shuffled; 
}
console.log(shuffle([1, 2, 3, 4, 5]));


/* A more elegant solution */

const shuffleBetter = items => {
	 return items
  	.map( item => ({value: item, random: Math.random()}))
    .sort((a ,b) => a.random - b.random)
    .map( item => item.value);
}
console.log(shuffleBetter([1, 2, 3, 4, 5]));