I am having two arrays,
the first array contains:
1, 2, 3, 4, 5
and the second one contains:
100, 200, 300, 400, 500
the result should be:
[ [ '1', '100' ],
[ '2', '200' ],
[ '3', '300' ],
[ '4', '400' ],
[ '5', '500' ] ]
I am having two arrays,
the first array contains:
1, 2, 3, 4, 5
and the second one contains:
100, 200, 300, 400, 500
the result should be:
[ [ '1', '100' ],
[ '2', '200' ],
[ '3', '300' ],
[ '4', '400' ],
[ '5', '500' ] ]
Simply With forEach
method:
const a = [1, 2, 3, 4, 5]
const b = [100, 200, 300, 400, 500]
const c = [];
a.forEach((el, ind) => {
c.push([el+"", b[ind]+""])
});
console.log(c)
Or with reduce
method:
const a = [1, 2, 3, 4, 5]
const b = [100, 200, 300, 400, 500]
const c = a.reduce((acc, curr, ind) => {
acc.push([curr+"", b[ind]+""]);
return acc;
}, []);
console.log(c)
Tip: +""
is like doing .toString()
will convert number
into text
You can loop through the array assuming they are the same size. toString() will give you the strings you want.
const first = [1, 2, 3, 4, 5]
const second = [100, 200, 300, 400, 500]
var result= [];
for(var i=0; i<first.length; i++){
result.push([first[i].toString(), second[i].toString()]);
}
console.log(result);
If arrays are not the same size and you only want while values exist in both indexes you could check for null or undefined.
const first = [1, 2, 3, 4, 5, 600, 700, 800]
const second = [100, 200, 300, 400, 500, 600, 700]
var result= [];
for(var i=0; i<first.length; i++){
if(first[i] && second[i]){
result.push([first[i].toString(), second[i].toString()]);
}
}
console.log(result);