var randomArray = [
'a','b', 'c'
];
const randomize = () => {
let tempArray = randomArray;
let randomIndex = Math.floor(Math.random()*randomArray.length);
let randomItem = randomArray[randomIndex];
// remove item
randomArray.splice(randomIndex, 1);
// return item
return randomItem;
}
for (let i = 0; i < randomArray.length; i ) {
console.log(randomize())
}
I'm trying to return items based on the length of the array (3) but for whatever reason I only return (2).
CodePudding user response:
As the size of the array is reduced, you shouldn't also increment i
. As both its length
and i
move with a step, you are ending the loop too soon. You just want to check the length
:
var randomArray = [
'a','b', 'c'
];
const randomize = () => {
let randomIndex = Math.floor(Math.random()*randomArray.length);
let randomItem = randomArray[randomIndex];
// remove item
randomArray.splice(randomIndex, 1);
// return item
return randomItem;
}
while (randomArray.length) {
console.log(randomize())
}
Not your question, but note that splice
returns the slice that was "spliced" out of the array, so you can use that instead of assigning the value to a variable:
var randomArray = [
'a','b', 'c'
];
const randomize = () => {
let randomIndex = Math.floor(Math.random()*randomArray.length);
// remove & return the item
return randomArray.splice(randomIndex, 1)[0];
}
while (randomArray.length) {
console.log(randomize())
}
CodePudding user response:
You need a diffrerent loop and check just the length of the array.
var randomArray = ['a','b', 'c'];
const randomize = () => {
const randomIndex = Math.floor(Math.random() * randomArray.length);
return randomArray.splice(randomIndex, 1)[0];
}
while (randomArray.length) {
console.log(randomize())
}
CodePudding user response:
You are removing the item from the list when you call randomize()
, therefore your code only runs twice. Instead, you could use a copy of the array in your randomize()
function. We can do this with the .slice()
method. This will allow us to preserve the values of randomArray
:
var randomArray = [
'a','b', 'c'
];
let tempArray = randomArray.slice();
const randomize = () => {
let randomIndex = Math.floor(Math.random()*tempArray.length);
let randomItem = tempArray[randomIndex];
// remove item
tempArray.splice(randomIndex, 1);
// return item
return randomItem;
}
for (let i = 0; i < randomArray.length; i ) {
console.log(randomize());
}
CodePudding user response:
var randomArray = [
'a','b', 'c'
];
var count = randomArray.length;
const randomize = () => {
let tempArray = randomArray;
let randomIndex = Math.floor(Math.random()*randomArray.length);
let randomItem = randomArray[randomIndex];
// remove item
randomArray.splice(randomIndex, 1);
// return item
return randomItem;
}
for (let i = 0; i < count; i ) {
console.log(randomize())
}