Comprehending the inner workings of the reduce() method

After spending hours reading and watching videos to understand the reduce function, I finally had a breakthrough. It wasn't until I took a break, made some food, and came back to my computer that it all clicked. Now, I confidently grasp how the reduce function works.

However, I still find myself puzzled by why the first example below functions correctly while the second one does not.

Source: Eloquent Javascript Ch. 5 §Flattening

This code snippet 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 attempted to modify the code by turning the variable into a function, only to encounter an issue. The following code snippet returns undefined, leaving me uncertain about what went wrong:

This code snippet 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

Curious as to why the first approach is successful while the second one fails, I suspect there might be a minor detail that has eluded my understanding.

Answer №1

It is important to use the return statement in the flattened function.

function flattenedArray(inputArray){
  return inputArray.reduce(function(accumulator, currentValue) {
    return accumulator.concat(currentValue);
  });
}

Answer №2

The issue stems from the fact that the function flattened does not have a return statement.

function flattened(arr){
  /* The “return” statement needs to be added here */ arr.reduce(function(a, b) { // The outer wrapper function "flattened" is missing a return statement
    return a.concat(b); // However, the inner function "reduce" does have a return statement
  });
}

Although the function inside returns something, the main function itself does not.

Answer №3

To achieve the desired output, the flattened() function should be implemented as shown below:

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

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Locating elements with Selenium Webdriver using xpath

<a style="color:White;" href="javascript:__doPostBack('dnn$ctr674$Case$gvCaseSearchDetails','Page$777')">777</a> Can anyone help with writing an xpath for the HTML code above? The goal is to locate elements using the identi ...

Where is the session management functionality situated within an OAuth-enabled web application?

When creating an oauth service (such as for Facebook or Gmail) enabled web application using Angular or React, where should session management be located? Should user sessions be maintained on the hosted server or within the oauth service itself? This is ...

Tips for efficiently updating state in React.js dynamically?

Is there a way to dynamically update the state of CurrentIndex whenever a user is selected? Currently, it is hardcoded to 0 but I would like to change that. I need the currentIndex to be updated whenever a user from the list is clicked. The SidePan ...

Is there a way to make jQuery Fancybox recognize my object as a valid parameter for opening?

I'm dealing with some HTML code that looks like this: <div id="logos" class="downloadlist"> <ul> <li><a href="/toolkit/logos/download.jpg" data-image="images/toolkit/logos/one.jpg">First Logo</a></li> ...

Create a randomly generated value in a JSON format

{ "description": "AppName", "name": "appName", "partnerProfile": { "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="f19090b1969c90989ddf929e9c">[email protected]</a>", "firstName": "John", ...

Can we prevent a component from being mounted every time it is rendered by its parent component?

Is it possible to render the Child component within the Father component without mounting it and resetting its states when the Father component is rendered? I attempted to use the useMemo hook to render the Child component, but it still mounts the compone ...

Adjusting the text and background hues using JavaScript results in an immediate reversal

Attempting to dynamically change the text color and background color based on user input in the textbox. While it initially works, the color changes only flash for a brief moment before reverting back. <!DOCTYPE html> <html> <head> ...

ANGULAR: Issue with filtering an array by clicking a button is not functioning

I've been attempting to apply a filter to my array by using modulo on the id when clicking multiple buttons. I initially tried using pipe but was advised to stick with .filter(). Despite watching numerous online tutorials, I keep encountering errors o ...

Why is my Bootstrap Carousel Switching Images but Refusing to Slide?

I've encountered a problem with my bootstrap carousel. The slide effect doesn't seem to be working, even though I have added the "slide" CSS tag. Instead of sliding, the images just quickly change without any transition. Here are some key points ...

Tips on adding up the values of fields in arrays in mongoose

const PostSchema = new mongoose.Schema({ title: { type: String, }, text: { type: String, required: true, } postedBy: { type: mongoose.Schema.ObjectId, ref: "User", } likes: [{ type: mongoose.Schema.ObjectId, ref: " ...

Could someone please assist me in figuring out the issue with my current three.js code that is preventing it from

Recently, I decided to delve into learning three.js and followed the getting started code on the official documentation. However, I encountered a frustrating issue where the scene refused to render, leaving me completely perplexed. Here is my index.html: ...

Which specific transitionend (or animationend) event should I use for this application?

I'm feeling a bit lost when it comes to using transitionend (or if I should be using animationend in this scenario). I'm not sure whether to utilize var, node, or box. Essentially, I am a complete beginner in this case. My goal is to have my div ...

When using Ajax in Jquery and expecting data of type JSON, the response always seems

Looking to create a basic jQuery Ajax script that checks a user's discount code when the "Check Discount Code" button is clicked? Check out this prototype: <script> jQuery(function($) { $("#btn-check-discount").click(function() { c ...

Issues have arisen with the @keydown.ctrl and @keyup.ctrl event modifiers in Vue.js, as they are not properly responding

I have a project in VueJS where I need to implement a custom context menu that will pop up when the user hovers over specific elements on the page. This context menu is dynamic, meaning it changes as the user moves between different items. If the user hold ...

Leaflet: An issue occurred when attempting to retrieve a GeoJSON file from a multipolygon Layer

Here's the current issue: I have successfully implemented a MultiPolygon Layer in Leaflet, but I am encountering an error when trying to convert it to a GeoJSON object. This is my code snippet: let colecccionPoligonos=[]; const multiPolygonOptio ...

JavaScript code to allow two textboxes to be enabled at the same time when a checkbox is

One question I have regarding the code snippet below : <input id="myCheckBox" type="checkbox" name="alamatCat" onClick="apply(this.checked, 'textBox3', 'textBox4')"> OT Date </td> <td> From <input id="text ...

The jQuery keyup event initiates multiple times, increasing exponentially with each trigger

I recently added a search bar with auto-complete functionality to my website. The search bar queries the database for elements that begin with the text entered by the user as they type. Although it works well, I noticed that every time the user inputs ano ...

Method for creating a randomized layout grid in MaterialUI where each row contains a total of three columns

In the process of developing a React application that interacts with the reddit api and oAuth. Utilizing MaterialUI, I am currently experimenting with the Component to create a 3 column grid of images with dynamically generated column widths, maxing out a ...

Refresh Entity with Real-Time Data on Cesium

I have been attempting to showcase an entity moving within Cesium through the use of live/dynamic data. After trying various techniques and consulting past forums, particularly those from 2015-2016, I am still struggling to make it work. Despite my effort ...

Aligning a lowercase "i" element within a container

Is there a more effective way to center the "i" element within this div without using specific pixel margins that adjust based on hover? Below is my code snippet: HTML: <div class="nav-collapse"> <i class="fa fa-bars fa-2x" id="bars"></ ...