Javascript: How to insert a row at an index to a multidimensional array? - Stack Overflow

I am novice programmer in javascript. Kindly guide me in the right path.Below is a 3D array of size 2 x

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 acplish it? Thanks

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 acplish it? Thanks

Share Improve this question asked Oct 21, 2015 at 10:48 KarthikKarthik 1,0742 gold badges16 silver badges35 bronze badges
Add a ment  | 

3 Answers 3

Reset to default 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

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

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

DEMO

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./edit/angular-insert-row-matrix

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744184505a4562141.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信