I have an array var arr = [1,2,3,4,5]
and I want to add x
at a random position in the array.
I tried this
let n = arr.length;
let randomIndex = Math.floor(Math.random() * arr.length);
for (let i = randomIndex; i < n + 1; i++) {
arr[i+1] = arr[i];
arr[randomIndex] = 'x';
}
The expected output after calling the function above was [1,2,’x’,3,4,5] or [‘x’,1,2,3,4,5] or [1,2,3,4,’x’,5] But it didn’t work. Any suggestion would help
3
Answers
Use
splice
to insert at at particular position. The idiom| 0
is equivalent toMath.floor()
for positive numbers less than2^31
.Note that you need to use
arr.length+1
to ensure that one of the possible the random positions can be after the last element of the original array.It Should work perfectly.