-2

I am new to JavaScript.

I have the following 1-d arrays:

    m=[1,2,3,4]
    n=[5,6,7,8]

I want to convert the following in JavaScript:

    x=[[1,5], [2,6], [3,7], [4,8]]

How can I do this?

Thanks for your help in advance.

I am new to java-script

mrbright
  • 49
  • 5
  • 2
    So loop over one and build up a new array referencing the second. – epascarello Jul 08 '19 at 16:16
  • 1
    Welcome to StackOverflow! I appreciate that you're new, but the requirement here is that you show your work. You have to actually try to solve what you're doing instead of simply asking. – zfrisch Jul 08 '19 at 16:17
  • Hello and welcome to SO; to avoid downvotes in the future please read the following guide [mre] – Hasan Patel Jul 08 '19 at 16:18
  • You can just run a loop and create another array with values at index from first and seconds array. `const m = [1, 2, 3, 4];` `const n = [5, 6, 7, 8];` `let reultArray = [];` `for (var i = 0; i < m.length && i < n.length; i++)` `reultArray[i] = [m[i], n[i]];` `console.log(reultArray);` – nircraft Jul 08 '19 at 16:33

2 Answers2

1

Use a map to create a new array where the callback takes the item being processed as param 1, and its index as param 2.

const m = [1, 2, 3, 4]
const n = [5, 6, 7, 8]


const o = [...m].map((itm, idx) => [itm, n[idx]])

console.log(o)
Get Off My Lawn
  • 34,175
  • 38
  • 176
  • 338
0
function multiDimension(m, n) {
  var x = [];

  m.forEach(function(v, k) {
    x.push([m[k],n[k]]);
  });

  return x;
}

multiDimension([1, 2, 3, 4], [5, 6, 7, 8]);
Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
Mehul Patel
  • 21
  • 1
  • 3