Hender Elstein
Hender Elstein

Reputation: 87

randomly insert elements in arrays using jQuery

If I have an array of 10 elements (sequence is important)

and I want to insert four elements at random spots, without messing up the order of the existing array

what is the best way?

Thanks and Merry Christmas

Upvotes: 0

Views: 58

Answers (2)

charlietfl
charlietfl

Reputation: 171679

Use splice()

var a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var b = [20, 21, 22, 23];

for (i = 0; i < 4; i++) {
    var idx = Math.floor(Math.random() * a.length);
    a.splice(idx, 0, b[i]);
}

console.log(a)
// returns something like [23, 1, 2, 3, 22, 4, 5, 6, 7, 20, 8, 21, 9, 10]

Reference MDN Array.prototype.splice() docs

If this is not the expected output please provide a sample

Upvotes: 4

RicardoE
RicardoE

Reputation: 1725

Try this:

var myArray = [1,2,3,4,5,6,7,8,9,0];

for(i=0; i<4; i++) {
    var randomSpot = Math.floor(Math.random() * 10);    
    myArray[randomSpot] = i;
}

Upvotes: 0

Related Questions