1

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.

1
  • 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] Commented Sep 13, 2022 at 21:20

1 Answer 1

3

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

Sign up to request clarification or add additional context in comments.

3 Comments

cool but can you please explain what happened there? what is _ for example?
@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?
@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!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.