skip to Main Content

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


  1. Use splice to insert at at particular position. The idiom | 0 is equivalent to Math.floor() for positive numbers less than 2^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.

    const arr = [1,2,3,4,5]
    
    arr.splice((arr.length+1) * Math.random() | 0, 0, 'x')
    
    console.log(arr)
    Login or Signup to reply.
  2. let arr = ['apple', 'pear', 'banana'];
    arr[Math.floor(Math.random()*arr.length)]='tomato';
    console.log(arr);
    //tomato is not a fruit 
    Login or Signup to reply.
  3. It Should work perfectly.

    let arr = [1, 2, 3, 4, 5];
    let n = arr.length;
    let randomIndex = Math.floor(Math.random() * (n + 1)); // generate random index including the end of the array
    
    arr.splice(randomIndex, 0, 'x'); // insert 'x' at random index
    
    for (let i = n - 1; i > 0; i--) {
      let j = Math.floor(Math.random() * (i + 1)); // generate random index to swap with
      [arr[i], arr[j]] = [arr[j], arr[i]]; // swap elements at indices i and j
    }
    
    console.log(arr); // Output
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search