0

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

4
  • Please post the code you've tried. Commented Dec 23, 2014 at 21:32
  • Look at Array.splice Commented Dec 23, 2014 at 21:33
  • 1
    I don;t fully understand. If I have a list like [A,B,C] and i randomly inserted D, then wouldn't the resulting [A,D,B,C] mess up the order of the existing array? Commented Dec 23, 2014 at 21:33
  • Not too random if you don't want to mess with the existing order. Commented Dec 23, 2014 at 21:38

2 Answers 2

4

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

Sign up to request clarification or add additional context in comments.

Comments

0

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;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.