I´m trying to make an array from a few arrays.
for example.
array1= ['Joe','James','Carl','Angel','Jimmy',];
array2= ['22','11','29','43','56',];
array3= ['red','blue','orange','brown','yellow',];
I need to create a new array pushing by index. What i´m trying to do sis something like this
newArray=['Joe22red','james11blue','Carl29orange','Angel43brown','Jimmy56yellow']
¿How can I do that?
CodePudding user response:
array1= ['Joe','James','Carl','Angel','Jimmy'];
array2= ['22','11','29','43','56'];
array3= ['red','blue','orange','brown','yellow'];
newArray = []
for (let i =0; i<Math.max(array1.length, array2.length, array3.length); i ) {
newArray.push(`${array1[i]}${array2[i]}${array3[i]}`)
}
console.log(newArray);
CodePudding user response:
const array1= ['Joe','James','Carl','Angel','Jimmy',];
const array2= ['22','11','29','43','56',];
const array3= ['red','blue','orange','brown','yellow',];
const result = array1.map(
(item, index) => `${item}${array2[index]}${array3[index]}`
)
console.log(result);
CodePudding user response:
There's an approach that consider using Array.prototype.reduceRight() method. It can receive up to four parameters from which the first three can be used.
A one liner solution that works with three arrays with the same lenght:
array1=["Joe","James","Carl","Angel","Jimmy"],array2=["22","11","29","43","56"],array3=["red","blue","orange","brown","yellow"];
console.log(
array1.reduceRight((acc,curr,i) => [curr array2[i] array3[i], ...acc], [])
)