baconitus
baconitus

Reputation: 35

Create an array from others

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 is something like this :

newArray=['Joe22red','james11blue','Carl29orange','Angel43brown','Jimmy56yellow']

How can I do that ?

Upvotes: 1

Views: 78

Answers (4)

Nguyen
Nguyen

Reputation: 36

You can use map function to find out the result

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);

Upvotes: 2

A1exandr Belan
A1exandr Belan

Reputation: 4780

And if we don´t know how many arrays are? Here is solution

const array1= ['Joe','James','Carl','Angel','Jimmy',];
const array2= ['22','11','29','43','56',];
const array3= ['red','blue','orange','brown','yellow',];

const data = [array1, array2, array3];

const result = data[0].map((_, index) => data.map((arr) => arr[index]).join(''));

console.log(result);
.as-console-wrapper{min-height: 100%!important; top: 0}

Upvotes: 2

testing_22
testing_22

Reputation: 2585

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], [])
)

Upvotes: 1

YuTing
YuTing

Reputation: 6629

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);

Upvotes: 2

Related Questions