l-emi l-emi - 3 months ago 11
Javascript Question

Turning a list of numbers separated by line breaks into a line

I have this code which is supposed to add pairs of numbers and print out new numbers.

var a = [580563, 750269, 127553, 478126, 490797, 919298, 440977, 549169, 935253, 48340, 605950, 859831, 26818, 336881, 438690];
var b = [498030, 704160, 346646, 544826, 898396, 192725, 382888, 590117, 172659, 534225, 592230, 235547, 502236, 327531, 405165];

for (var i = 0; i < a.length; i++) {
var k = a[i] + b[i];
console.log(k);
}


This returns this:

1078593
1454429
474199
1022952
1389193
1112023
823865
1139286
1107912
582565
1198180
1095378
529054
664412
843855


How do I turn it into this:

1078593 1454429 474199 1022952 1389193 1112023 823865 1139286 1107912 582565 1198180 1095378 529054 664412 843855


Thanks!

Answer

Instead of logging the output for each index, concatenate a string and then handle output after the loop.

var a = [580563, 750269, 127553, 478126, 490797, 919298, 440977, 549169, 935253, 48340, 605950, 859831, 26818, 336881, 438690];
var b = [498030, 704160, 346646, 544826, 898396, 192725, 382888, 590117, 172659, 534225, 592230, 235547, 502236, 327531, 405165];

var k = '';
for (var i = 0; i < a.length; i++) {
    k += (a[i] + b[i]) + ' ';
}
console.log(k);

You can also keep track of each sum in an array, and join the elements with a space:

var k = [];
for (var i = 0; i < a.length; i++) {
    k.push(a[i] + b[i]);
}
console.log(k.join(' '));

And as user Arnauld mentioned, this can be reduced into a one-liner by using the map function.

Comments