Using reduce to create a single layred array


#1

Hey guys I would like to know how this piece of code works I understand how reduce works

let layeredArray = [[1,2], [2,4], [4,6],[6,8]];

let newArray = layeredArray.reduce( (acc, curVal, idx) => {
return acc + curVal;
});

//output [1, 22, 44, 66, 8]


#2

If you’re not asking about reduce, what are you asking about?
All I see in that code is reduce, there appears to be nothing else to talk about in it.
Judging by the output you say you get, the code is incomplete too.


#3

I dont understand why the number 1 and 8 are not being added together with everything also how is the code incomplete ?


#4

It doesn’t produce that output. It doesn’t produce any output.
You also say you understand reduce, but only show reduce, so surely you must mean some other piece of code.


#5

Im sorry can I show you a link ? After running the code on codecadmy’s javascript compiler it gave me that output also I do understand reduce that wasnt what I was asking I just dont get why the 1 and 8 aren’t being combined with the rest of the numbers


#6

not sure if you can view this but take a look if you can https://gist.github.com/f750a35781c633ac4f0601f4073cf8af


#7

You haven’t explained why you think 1 and 8 should be combined, or how they should be combined. From what I see 1 and 8 aren’t being treated any differently from anything else.

I’m not sure why you include reduce in your code when that isn’t what you’re asking, if it’s not related remove it from the question!

All I know is that you’re not asking about reduce. I don’t know what you’re looking for.

I might point out though, that addition between arrays is a strange thing to do. Maybe what you meant is concatenation:

[1].concat([1])  // [1, 1]

And if that is the issue then I definitely must suggest that you figure out how to do such operations before you involve reduce


#8

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.