简体   繁体   中英

Merge two of one dimensional array into two dimensional array javascript

I have n (but for now, let say just two) of one dimensional arrays like this image of my console :

在此处输入图片说明

And I want to merge these two arrays by the corresponding key and put it into two dimensional array :

The result is something like :

[["1 279 226,08" , "127"],[null , null],["-188 033,77", "154"],..... so on ......]

And the list of one dimensional array is dynamic, it could be more than 2 arrays.

So example if I have 3 arrays, then my two dimensional array would look like :

[ ["1 279 226,08" , "127" , "blabla"], [null , null , "blabla"], ["-188 033,77", "154", "blabla"], ..... so on ......]

Any ideas of implementing it would be appreciate.

This should do what you want.

 var arr1 = [1, 2, 3, 4, 5, 6]; var arr2 = [6, 5, 4, 3, 2, 1]; var arr3 = [7, 8, 9, 10, 11, 5]; var arr4 = [12, 34, 55, 77, 22, 426]; var arrCollection = [arr1, arr2, arr3, arr4]; // if array sizes are variable. // if not max = arrCollection[0].length will do var max = Math.max.apply(Math, arrCollection.map(function(a) { return a.length; })); var arrFinal = []; for (let i = 0; i < max; i++) { var arr = []; arrCollection.forEach(function(a) { arr.push(a[i]); }); arrFinal.push(arr); } console.log(arrFinal);

You can create this with two forEach() loops.

 var arr1 = [[1, 2], [3, 4], [5, 6]]; var arr2 = [[1, 2, 3], [4, 5, 6], [7, 8], [9, 10, 12, 14]]; let merge = function(arr) { var result = []; arr.forEach(function(e, i) { e.forEach(function(a, j) { if (!result[j]) result[j] = [a]; else result[j].push(a) }) }); return result; } console.log(JSON.stringify(merge(arr1))) console.log(JSON.stringify(merge(arr2)))

You could transpose the array with a nested loop and switch the indices for assigning the values.

 var array = [["1 279 226,08", null, "-188 033,77"], ["127", null, "154"], ["blabla", "blabla", "blabla"]], result = array.reduce(function (r, a, i) { a.forEach(function (b, j) { r[j] = r[j] || []; r[j][i] = b; }); return r; }, []); console.log(result);
 .as-console-wrapper { max-height: 100% !important; top: 0; }

Since all of your arrays have the same size, you can loop just on the lenght of the first array, ie a .

Then we pass to appendArrays the single value of a , b , ..., and we return the an array to push into merged

 var a = ["123", null, "ciao"] var b = ["321", 1, "pippo"] var c = ["111", 5, "co"] var merged = [] for (i = 0; i < a.length; i++) { merged.push(appendArrays(a[i], b[i], c[i])); } console.log(merged); function appendArrays() { var temp = [] for (var i = 0; i < arguments.length; i++) { temp.push(arguments[i]); } return temp; }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM