I have a set of arrays that have multiple bits of data that I want to arrange into a new array of data. This is what I have:
const dateArray = ["9/13/2022", "9/13/2022", "9/13/2022", "9/13/2022","9/13/2022"]
const timeArray = ["00:00", "00:01", "00:02", "00:03", "00:04"]
const integerArray = [1,2,3,4,5]
This is what I want:
{
row0: ["9/13/2022", "00:00", 1],
row1: ["9/13/2022", "00:01", 2],
row2: ["9/13/2022", "00:02", 3],
row3: ["9/13/2022", "00:03", 4],
row4: ["9/13/2022", "00:04", 5]
}
Thanks for any info you could provide, I've tried to do map, reduce and group but I haven't had exactly what I want to come back and I'm losing my mind keeping track of what I've tried.
-
Will all the three arrays have equal number of items. If that is the case you can just create a for loop on length of any array. Then insert an object rowIndex as dateArray[i], timeArray[i] and integerArray[i]Harshit Pant– Harshit Pant2022年09月13日 21:20:53 +00:00Commented Sep 13, 2022 at 21:20
1 Answer 1
Using Array#reduce:
const dateArray = ["9/13/2022", "9/13/2022", "9/13/2022", "9/13/2022","9/13/2022"]
const timeArray = ["00:00", "00:01", "00:02", "00:03", "00:04"]
const integerArray = [1,2,3,4,5]
const res = dateArray.reduce((acc, _, i, dates) => ({
...acc, [`row${i}`]: [dates[i], timeArray[i], integerArray[i]]
}), {});
console.log(res);
answered Sep 13, 2022 at 21:17
Majed Badawi
28.5k4 gold badges30 silver badges56 bronze badges
Sign up to request clarification or add additional context in comments.
3 Comments
Chris G
cool but can you please explain what happened there? what is
_ for example?Majed Badawi
@ChrisG as linked in the docs, the second param is the current-value which we're not using in the solution.
_ is just a common-practice to tell that this variable is to be ignored. Does this answer your question?gilly2chilly
@MajedBadawi, thank you so much for the prompt answer and the breakdown afterwards, I tried so many attempts of reduce and see now why my code flopped, thank you!
Explore related questions
See similar questions with these tags.
lang-js