Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to combine 3 arrays into one with the same index - JavaScript

I currently have 3 arrays that I would like to combine together and have them appear as an object.

1. dataArr = [ 0. 123323, 1. 8930, 2. "9,321", 3. 103001 ]

2. titleArr = [ 0. "New", 1. "Old, 2. "Confirmed", 3. "Not Available"    ]

3. typeArr = [  0. "Online", 1. "In-Store" 2. "Walk In", 3. "Appointment"   ]

I would like all these be one array and have an array of objects with the same index such as.

newArr = [0. { data: 123323 , title: "New", type: "Online"} 1. {data ... } ... ] 

I've attempted using a mapping method which I am getting the results for two of the arrays but the 3rd array typeArr is inserting an array of 4 objects for every index rather then its respective index.

Console.log = [ 0. data: 123323, title: New, type: [ 0. "Online", 1. "In-Store, 2. "Walk In" 3. "Appointment" ] ]

Here is my code:

const combineArr = dataArr.map((data, index) => ({
        data,
        title: titleArr[index]
    }));

    const newArr = combineArr .map((type, index) => ({
        type,
        data: typeArr[index]
    }));

In this case I am using two seperate mapping functions in attempt to create a new array. I believe this is where I am getting confused. Is there a way of handling all 3 arrays in one mapping function?

like image 640
stepheniok Avatar asked Sep 15 '25 18:09

stepheniok


1 Answers

Assuming the same index order, you can use the function map as follow:

let dataArr = [ 123323, 8930, 9321, 103001 ],
    titleArr = [ "New", "Old", "Confirmed", "Not Available"    ],
    typeArr = [  "Online", "In-Store", "Walk In", "Appointment"   ],
    result = dataArr.map((data, i) => ({data, title: titleArr[i], type:  typeArr[i]}));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 66
Ele Avatar answered Sep 17 '25 09:09

Ele