0

Insert a row of elements into a multi-dimensional array based on index

For Example:

MultiArray = new Array(5);
MultiArray [0] = new Array(2);
MultiArray [0][0] = "Tom";
MultiArray [0][1] = "scientist";
MultiArray [1] = new Array(3);
MultiArray [1][0] = "Beryl";
MultiArray [1][1] = "engineer";
MultiArray [1][2] = "Doctor";
MultiArray [2] = new Array(2);
MultiArray [2][0] = "Ann";
MultiArray [2][1] = "surgeon";
MultiArray [3] = new Array(2);
MultiArray [3][0] = "Bill";
MultiArray [3][1] = "taxman";
MultiArray [4] = new Array(2);
MultiArray [4][0] = "Myrtal";
MultiArray [4][1] = "bank robber";
MultiArray.splice(1,0, new Array(2){"two","one"});

The last line in my code didn't work. I am not sure if the rest of the code is right neither.

Now can anyone please let me know whether I can insert a row of elements somewhere in between and move the remaining elements one index down?

JB Nizet
694k94 gold badges1.3k silver badges1.3k bronze badges
asked Nov 6, 2012 at 12:31
5
  • java != javascript. I removed the java tag. Commented Nov 6, 2012 at 12:33
  • 1
    @Sushil why? It's absolutely ok to write new Array(10) Commented Nov 6, 2012 at 12:42
  • @Sushil: No, its not :). Go ahead and try: var a = new Array(10); console.log(a.join("wat")); Commented Nov 6, 2012 at 12:46
  • MultiArray.splice(1,0, MultiArray.splice(2,1) ); Is this allowed? I tried this because the splice() returns a row of array but its not working. Commented Nov 6, 2012 at 12:56
  • Raghul, perhaps splice does not what you think it does? Check the splice doc on MDN to make sure. I wrote an example from your code and it works exactly like it should. Commented Nov 6, 2012 at 13:00

2 Answers 2

4

You accidently wrote new Array{} which is wrong - your command should be either:

MultiArray.splice(1,0, new Array(2)("two","one")); // no curled brackets!!

or even better

MultiArray.splice(1,0, ["two","one"]);

Altogether, in javascript the new Array() notation should be avoided (js automatically controls the dimension of it's arrays, no need to preallocate or declare it). Instead you can write:

MultiArray = [];

So, you can directly write:

MultiArray = [[ "Tom","scientist"],["Beryl","engineer","Doctor"],
 ["Ann","surgeon"],["Bill","taxman"],["Myrtal","bank robber"]];
MultiArray.splice(1,0, ["two","one"]);
answered Nov 6, 2012 at 12:41
Sign up to request clarification or add additional context in comments.

Comments

2

Try:

MultiArray.splice(1,0, ["two","one"]);
answered Nov 6, 2012 at 12:40

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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.