jward01
jward01

Reputation: 759

Understanding how the reduce() function works

I am just ensuring that I know how this function works. I read material and watched videos on the reduce function for probably 3 hours last night, I did not get it. I stepped away from my computer, made some food, watched a TV show, and then looked at the computer again and BAM! I got it. I know how the reduce function works now.

I just don't know why the first example below works while the second doesn't.

source: Eloquent Javascript Ch. 5 §Flattening

This works:

var arrays = [[1, 2, 3], [4, 5], [6]];

var flattened = arrays.reduce(function(a, b) {
  return a.concat(b);
});

flattened; //=>[1, 2, 3, 4, 5, 6]

I tried to fiddle around with the code, to change the variable to a function. And somehow, I broke it. This below returns undefined, and I am not sure why.

This doesn't work:

var arrays = [[1, 2, 3], [4, 5], [6]];

function flattened(arr){
  arr.reduce(function(a, b) {
    return a.concat(b);
  });
}
flattened(arrays); //=> undefined

Why does the first function work, but not the second? I'm sure it's something small I am missing.

Upvotes: 0

Views: 112

Answers (3)

Sebastian Simon
Sebastian Simon

Reputation: 19485

Because the function flattened doesn’t return anything.

function flattened(arr){
  /* “return” needs to be here */ arr.reduce(function(a, b) { // No return from the outer wrapper function “flattened”
    return a.concat(b); // return from the inner function “reduce”
  });
}

The function within it does return something, but the containing function doesn’t.

Upvotes: 1

Shambhavi
Shambhavi

Reputation: 335

The flattened() needs to return the value like this:

var arrays = [[1, 2, 3], [4, 5], [6]];

function flattened(arr){
return arr.reduce(function(a, b) {
  return a.concat(b);
});
}
flattened(arrays);

Upvotes: 1

Zachary Kuhn
Zachary Kuhn

Reputation: 1152

You need to return from the flattened function.

function flattened(arr){
  return arr.reduce(function(a, b) {
    return a.concat(b);
  });
}

Upvotes: 2

Related Questions