Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Concat Values of Two Arrays

I have two arrays like this:

const a = ['a', 'b', 'c', 'd'];
const b = ['1', '2', '3', '4'];

I'm trying to make a new array like this:

const c = ['a1', 'b2', 'c3', 'd4'];

I tried it this way:

const c = [];
c.push([`${a[0]}${b[0]}`, `${a[1]}${b[1]}`, `${a[2]}${b[2]}`, `${a[3]}${b[3]}`]);

With actually looping through data and doing this took 17400ms.

I took out the c.push([........]); and it dropped to 1250ms.

Why does this take so long to do?

And what is the best way to do this?

like image 227
cocacrave Avatar asked Sep 13 '25 04:09

cocacrave


2 Answers

you can use .map to achieve that. map a, then use index on each loop to get element of b.

const a = ['a', 'b', 'c', 'd'];
const b = ['1', '2', '3', '4'];

var c = a.map(function (d, i) {
    return d + String(b[i])
})

console.log(c)
// ["a1", "b2", "c3", "d4"]

cleaner code using es6:

var c = a.map((d, i) => `${d}${b[i]}`)
like image 136
novalagung Avatar answered Sep 15 '25 19:09

novalagung


A simple loop.

const a = ['a', 'b', 'c', 'd', 'e'];
const b = ['1', '2', '3'];
var result = [];

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

alert(result);
like image 21
Ronnie Royston Avatar answered Sep 15 '25 17:09

Ronnie Royston