0

Is it possible to merge (or maybe convert?) two large 1D arrays (of tens of thousands of items) into one 2D array so that columns of 2D array are the element wise items from each of the 1D array?

I mean the following:

a1 = [1,2,3,4,5,6,7,8,9,10]
a2 = [101,102,103,104,105,106,107,108,109,110]

result = [[1,101],[2,102],[3,103],[4,104],[5,105],[6,106],[7,107],[8,108],[9,109],[10,110]]

There are a few possible methods given in Python in this Merge Link here and I have to do exactly the same but in Javascript. Trying concat, merge but doesn't give the expected result.

Thanks

Bilal
  • 43
  • 1
  • 11

2 Answers2

1

you could use map operation returning the item from a1 and the indexed element of a2 like this:

const result = a1.map((item,index) => {return [item,a2[index]]})

Dont forget to check if the lenght is the same!

  • 1
    Thanks Daladier. The above (in addition to two extra steps) works for me. The lengths of the arrays are in tens of thousands which I shorten by filtering (with larger incremental steps) as a1Short = a1.filter(function(el, idx){ return ((idx) % inc) == 0; // inc is calculated as a step to jump to get only 1000 items }), and doing the same with a2, and then applying map function as above and it worked. Once again thanks – Bilal Jan 09 '19 at 01:24
  • You're wellcome, Bilal! – Daladier Sampaio Jan 09 '19 at 11:06
0

You can merge the elements from the two 1d arrays by each element and get the required 2d array as follows:

var a1 = [1,2,3,4,5,6,7,8,9,10];
var a2 = [101,102,103,104,105,106,107,108,109,110];
var resultArr = [];

for (let i = 0; i < a1.length; i++) {
    resultArr.push([a1[i], a2[i]]);
};

console.log(resultArr); // prints the result

The Output:

[[1,101],[2,102],[3,103],[4,104],[5,105],[6,106],[7,107],[8,108],[9,109],[10,110]]
prasad_
  • 12,755
  • 2
  • 24
  • 36
  • Thanks prasad_. I actually tried the above but since I had to loop over extremely large arrays (tens of thousands) a number of times to draw charts for each of the arrays, the browser was either crashing multiple times or it would pause processing due to a long time to spend processing all those. I'm sorry that I forgot to mention that I was working with very large arrays. What's working for me is I filter both arrays to shorter (but same) lengths and then applying map – Bilal Jan 09 '19 at 01:21
  • I just edited the question accordingly, and again apologies for missing the vital information – Bilal Jan 09 '19 at 01:28