0

i have 2 2D array, and want to merge a[0] with b[0]

var a=[["a","b","c"],["d","e","f"]];
var b=[["1","2","3"],["4","5","6"]];

console.log(a[0].splice(1,2,b[0]));
its return ["a",["1","2","3"]]

i need to archive ["a","1","2","3"] for a[0]

can any body show how ?

Rio Arfani
  • 89
  • 9

2 Answers2

0

You can use spread syntax

Spread syntax allows an iterable to expand in places where 0+ arguments are expected.

var a=[["a","b","c"],["d","e","f"]];
var b=[["1","2","3"],["4","5","6"]];

//if you are trying to achieve all elements in single array then
var result = [...a[0], ...b[0]];
console.log(result);

//if you are trying to achieve single element from first array and all from other then
var result = [...a[0][0], ...b[0]];
console.log(result);

Good article on Spread syntax

Prasad Telkikar
  • 15,207
  • 5
  • 21
  • 44
0

From docs, syntax of Array.splice is

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

As you can see, you can add more than 1 element to the array e.g. arr.splice(0,0,4,5) where you are adding 2 values (4 & 5) into array. With b[0] as 3rd parameter, you are adding the whole array at a particular index. To add individual value, you need to spread the values of array. You can use spread syntax for that. With that arr.splice(0,0,...[1,2]) will become arr.splice(0,0,1,2)

var a=[["a","b","c"],["d","e","f"]];
var b=[["1","2","3"],["4","5","6"]];
a[0].splice(1,2,...b[0])
console.log(a[0]);
Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59