5

I am novice programmer in javascript. Kindly guide me in the right path.

Below is a 3D array of size 2 x 3 x 3

"items": [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ]

Now, I need to insert a row, something like [ [19,20,21], [22,23,24], [25,26,27] ] at an index 1 or 2.

I tried with splice function, but all in vain.

Being a multi dimensional array, I don't know what value goes into the itemN parameter of the splice function.

items.splice(insertIndex, 0, `????`); 

How can I accomplish it? Thanks

3 Answers 3

7

use splice with deleteCount 0 (second parameter). as thrid param you enter the 2-dimensional array you want to add.

var items = [ [ [1,2,3], [4,5,6], [7,8,9] ], [ [10,11,12], [13,14,15], [16,17,18] ] ];
var add = [ [19,20,21], [22,23,24], [25,26,27] ];
items.splice(insertIndex, 0, add);

working example here: jsfiddle

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

2 Comments

Well i am confused. The current items array has already value at index 1. Then why did it shifted that value to index 2 and added the new value at index 1?
@HarshMakani - The splice function will insert the items at the specified index
1

You can pass complete array which you want to insert to splice parameter, like:

items.splice(2, 0,[ [19,20,21], [22,23,24], [25,26,27] ]);

DEMO

Comments

0

The accepted answer is good.

I make an demo to insert middle row in angular as reference.

I share for whom concerned.

    textarray = [
        [{ text: "Content 1" }, { text: "Content 2" }],
        [{ text: "Content 3" }, { text: "Content 4" }]
      ];
      rowindex = 1;
      insertmiddle() {
        let size = this.textarray[0].length;
        this.textarray.splice(this.rowindex, 0, 
             Array(size).fill({ text: "Content", tag: "Content" }));
      }

https://stackblitz.com/edit/angular-insert-row-matrix

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.