Ratan Uday Kumar
Ratan Uday Kumar

Reputation: 6492

How to concat javascript array

let A = ["u23", "c35",-----so on];

let B = ["123", "234", ---- so on];

both a and b indexes count are 100 and same

Expected output C = ["u23,123", "c35,234", ---- so on];

I need to achieve output in very few steps without using complex steps of for loop.

ECMAScript 6 and above also will be fine.

Upvotes: 0

Views: 119

Answers (2)

Sebastian Kaczmarek
Sebastian Kaczmarek

Reputation: 8515

You have to loop at least once - no other option. This is one of the possible solutions:

let A = ["u23", "c35", "d34"];
let B = ["123", "234", "345"];

let C = A.map((el, i) => el + "," + B[i]);
console.log(C);

The above solution may be improved by using a standard for-loop:

let C = [];
for (let i = 0; i < 1e6; i++){
  C.push(A[i] + "," + B[i]);
}

and you can improve it further by modifying one of the input arrays instead of creating a new array:

for (let i = 0; i < 1e6; i++){
  A[i] += "," + B[i];
}

You can compare the performance of each of the three above in the repl I've created here.

After a few runs, you'll notice that the last method is the fastest. It's because in the second example there's a new array C created and it has length of 0. With every .push(), the array has to be stretched which takes time. In the third example, you already have an array with the right size and you only modify its entries.

The thing which will always steal time is the string concatenation. You can play with my solutions by replacing the string concatenation with simple addition (as numbers) and you'll see that it makes the operation much faster. I hope it sheds some light on your problem.

Upvotes: 6

Rohan Agarwal
Rohan Agarwal

Reputation: 2609

let newArr =[];
A.forEach((el, index)=> {
  newArr.push(el);
  newArr.push(B[index]);
}

The newArr is now in your required format.

Upvotes: 0

Related Questions