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
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
D, then wouldn't the resulting [A,D,B,C] mess up the order of the existing array?