0
Is there a way to remove a particular value from an array?
I have an array/list that has 8 values. I want to randomly choose a value, assign it to a variable and then remove that value from the array so that only 7 values left. how do I do this?
11 Antworten
+ 9
1) create a function to get random number in a given range first (this will be used to get a random index)
2) next we will select random index
3) save the value to temp variable
4) remove the value from the array using splice method
function randVal(min, max) {
return Math.floor(Math.random()*(max - min + 1) + min);
}
arr = [1,2,3,4,5,6,7,8];
ind = randVal(0, arr.length-1);
temp = arr[ind];
arr.splice(ind, 1);
+ 11
The splice method return an array with the items removed, so you can shorten the two last lines of @Burey code:
temp = arr.splice(ind, 1)[0];
+ 6
nice one visph :]
+ 5
The number of items of an array is defined in the array.length attribute ^^
+ 4
if i send 0 and arr.length-1 in the first iteration (arr.length === 8)
i get the following
Math.floor(Math.random()*(7-0+1)+0);
Math.random is in the range of [0.0, 1.0) (1.0 not included)
so let's say i get 0.88 from Math.random()
so 0.88 * (7-0+1) + 0 is actually 0.88 * 8 == 7.04
floor(7.04) that and what you get?
7, which is the last index in the array at that given moment :)
of course any value above 0.88 will also produce tbe same outcome in this scenario
and even some values velow
+ 4
omg
SoloLearn lottery
best
idea
ever
xD
+ 3
wither way
the inside of the brackets is evaluated before
+ 1
@Burey, If I am reading the code above correctly it means it can never choose the last value in an array. As in, if I have 8 values in the array, by adding that 1 in the brackets the highest possible value of the bracketed result is 7 and coupled by the fact that math.floor is not inclusive of 1 my random selection will never choose the index value 7 which is the 8th value in an array of length 8. No?
+ 1
@Burey, --> so 0.88 * (7-0+1) + 0 is actually 0.88 * 8 == 7.04
I thought the order of operations follows that addition is done first so it is evaluated as '0.88*6 ==5.28. I had ignored the rule regarding Associativity and that Subtraction and Addition are the same level of order and are evaluated left to right whichever comes first.
0
Visph, thanks!
- 2
you can use delete example
in the following array
var days=["Sun","Mon","Tue"];
you can remove a particular day like
delete days[1];
and a particular value will be removed