Home > OS >  How can I merge 2 arrays into 1 in Javascript?
How can I merge 2 arrays into 1 in Javascript?

Time:11-03

I have input as p1= 1,2,3 and p2=100,200,300. I need to create a function that will get me:

[ ['1', '100'], ['2', '200'], ['3', '300'] ]

I tried to make it into a string but the issue is that I'm getting this output:

['[1, 100]', '[2, 200]', '[3, 300]']

Here's the code:

'use strict'

var readline = require('readline');
var rl = readline.createInterface({
  input: process.stdin,
  output: process.stdout,
  terminal: false
});

rl.question('', (p1) => {
  rl.question('', (p2) => {
    p1 = p1.split(", ")
    p2 = p2.split(", ")
   
    console.log(merge(p1,p2))

    rl.close();
  })
});

// DO NOT CHANGE ABOVE THIS LINE!!!!

const merge = function(p1,p2){
    for(let i=0;i<p1.length;i  ){
       
        p1[i]="[ " p1[i] ", " p2[i] " ]"
    }
    return p1;
} // Write this function

CodePudding user response:

As long as both arrays have de same length this will do the trick

function merge(p1, p2){
  const result = [];
  for(let i = 0; i<p1.length; i  ){
    const temp = [];
    temp.push(p1[i]);
    temp.push(p2[i]);
    result.push(temp);
  }
  return result;
}

CodePudding user response:

Abstracted a bit of your code, but this seemed to work

const p1 = ["1","2","3"]
const p2 = ["100","200","300"]

const newArray = []
for(let i = 0; i < p1.length; i  )
{
    newArray.push([p1[i], p2[i]])
}

Hope that helps!

CodePudding user response:

you can approach this this way:

p1 = [1,2,3];
p2 = [100, 200, 300];

let wanted1 = p1.map((x, y) => {
    return newArray = [x, p2[y]];
});

//wanted1 will equal: [[1, 100],[2, 200],[3, 300]]
  • Related