First of all sorry for the long title, I really didn't know how to word it better.
In the middle of solving _.shuffle in underscore, I encountered the use of splice. Here is my original code :
shuffle = function(array) {
var shuffledArray = [];
var total = array.length;
var copiedArray = array.slice();
while (total){
var randomNum = Math.floor(Math.random() * total);
shuffledArray.push(copiedArray.splice(randomNum,1));
total--;
}
return shuffledArray;
};
var originArray = [1, 2, 3, 4];
console.log(shuffle(originArray));
However after testing just I realized it will return each value inside a [ ], instead of just the value.
i.e.
[ [ 4 ], [ 3 ], [ 1 ], [ 2 ] ]
//instead of [ 4, 3, 1, 2]
When I changed this line (added '[0]' after the deleteCount in splice)
shuffledArray.push(copiedArray.splice(randomNum,1));
into this
//edited
shuffledArray.push(copiedArray.splice(randomNum,1)[0]);
the return array that I get is what I wanted, which is
[ 3, 1, 2, 4 ] //values are not in [ ]
Can someone explain how adding [0] after splice() makes the value not return in [ ] or why not having [0] does?