简体   繁体   中英

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.

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.

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

The newArr is now in your required format.

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