0

How can I pop the random chosen out of the array?
var number = ["a", "b", "c"];
var random = number[Math.floor(Math.random()*number.length)];

3 Answers 3

2

use splice

var number = ["a", "b", "c"];
var random = Math.floor(Math.random()*number.length);

console.log(number[random], ' is chosen');
var taken = number.splice(random, 1);

console.log('after removed, ', number);
console.log('number taken, ', taken);

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, but I dont understand the (random, 1), what does number 1 stand for?
2

Use splice and the random number as the index.

number.splice(random, 1);

Comments

1

You can use Splice to remove a certain number of items from an array. This method will altar the original array and return the values removed.

The first argument in the Splice method is the starting point. The second argument is the number of items to remove.

Example:

//            0    1    2
var array = ["a", "b", "c"];
var splicedItem = array.splice(1,1);

// The array variable now equals ["a", "c"]
console.log("New Array Value: " + array);
// And the method returned the removed item "b"
console.log("Spliced Item: " + splicedItem);

You can also use a negative number in the first argument to begin counting backwards from the end of the Array.

Example:

//            -6   -5   -4   -3   -2   -1
var array2 = ["a", "b", "c", "d", "e", "f"];
var splicedItem2 = array2.splice(-3, 2);

// The array2 variable now equals ["a", "b", "c", "f"]
console.log("New Array Value: " + array2);
// The values removed were "d" and "e"
console.log("Spliced Item: " + splicedItem2);

You can even insert new items into the Array by including additional arguments. You also don't need to return the spliced items to a new variable if you don't want to.

Example:

var array3 = ["a", "b", "c", "d", "e", "f"];

array3.splice(2, 2, "Pink", "Mangoes");

// The array3 value is now ["a", "b", "Pink", "Mangoes", "e", "f"]
console.log("New Array Value: " + array3);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.