Exploring the world of functional programming within nested arrays

I have been shifting towards functional programming over imperative programming recently.

Imagine I have a nested array data structure and my goal is to update the values of the innermost arrays. What approach would be most effective?

Here is the imperative code for transformation:

for (let i = 0; i < dataSheet.length; i++) {
    for (let j = 0; j < dataSheet[i].questions.length; j++) {
        for (let k = 0; k < dataSheet[i].questions[j].answers.length; k++) {
            dataSheet[i].questions[j].answers[k].name += ' (edited name)';
            dataSheet[i].questions[j].answers[k].value = 1 + dataSheet[i].questions[j].answers[k].value / 10;
        }
    }
}

I've devised two methods for achieving this:

Using map():

dataSheet
.map(section => section.questions
    .map(question => question.answers
        .map(answer => (
            {
                ...answer,
                name: answer.name + ' (edited name)',
                value: 1 + (answer.y / 10),
            }),
        ),
    ),
);

Using forEach():

dataSheet.forEach(section => section.questions
    .forEach(question => question.answers
        .forEach(answer => (
            {
                ...answer,
                name: answer.name + ' (edited name)',
                value: 1 + (answer.y / 10),
            }),
        ),
    ),
);

All three achieve the same result, but none of them seem significantly better. The pyramid-like structure in both functional approaches doesn't enhance readability. The situation could worsen with additional levels of nesting.

Transitioning from imperative to functional programming does not offer clarity or maintainability improvement in this case. Moreover, performance might suffer as each object modification creates a new copy.

In this scenario, do you believe sticking with imperative coding is preferable? Or is there an alternative method that could work better?

Answer №1

Transitioning from imperative to functional programming may not necessarily enhance the clarity, readability, or maintainability of the code in this scenario. It could potentially be slower due to creating a new copy for each modified object.

One could argue that utilizing

.map(answer => [code block])

is more easily readable compared to

for (let k = 0; k < dataSheet[i].questions[j].answers.length; k++) [code block]

Even though nesting cannot be eliminated with the map method, it offers numerous advantages that contribute to better maintenance of the codebase.

  • Avoidance of managing i, j, k variables reduces the likelihood of introducing bugs.
  • The main benefit of functional programming is purity. While the map operation might be slower in simpler cases, it enables immutable input that can be utilized and stored elsewhere without compromising integrity.

(Using forEach would not be suitable as it does not return anything)

In light of this, embracing the functional approach is recommended, as there are no substantial advantages to sticking with imperative programming except for minor performance gains.

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

Ubuntu is experiencing a DNS problem. While the URL request works perfectly on MacOSX, it is unsuccessful on Ubuntu

A custom nodeJS script has been developed to utilize the require('request').post() method. The script executes successfully on MacOSX (Travis), however encounters issues on Ubuntu (Travis). To troubleshoot, experimentation with NodeJS 'https ...

Mastering the art of transitioning between DIV elements

I am looking to implement a rotating three-card display on click, and have come up with the following code: $('.box1').click(function(){ $('.box1').toggleClass('removeanimate'); $(this).toggleClass('go'); ...

Pictures are not showing up in the gallery after they have been saved

if (action.equals("saveToGallery")) { JSONObject obj = args.getJSONObject(0); String imageSource = obj.has("imageSrc") ? obj.getString("imageSrc") : null; String imageName = obj.has(" ...

Is there a way to automatically clear the text field value after submitting?

Greetings everyone, I'm looking for guidance on removing the text field content once I click submit. I have a button labeled "senden" and my goal is to clear the text fields and uncheck the checkbox after clicking this button. I've attempted se ...

Unify your navigation with Bootstrap 5 - harnessing the power of two navs

I am struggling with a code that has three identical blocks, each with at least two navigation items and one tab content. The issue I am facing is that I can't figure out how to deselect the active item in the other lists when one is clicked on. I c ...

Align elements on the left side with some space between them

Having trouble displaying a list of images inline within a div. When I float them left, they leave a lot of space and do not display properly. Can anyone help me with this issue? See screenshot below: Here is my html code: <div class="col75"> & ...

Finding a character that appears either once or thrice

In my work on JavaScript regex for markdown formatting, I am trying to match instances where a single underscore (_) or asterisk (*) occurs once (at the beginning, end, or surrounded by other characters or whitespace), as well as occurrences of three under ...

Use map.fitBounds in MapBox to continuously adjust the map view to show only the visible features on the map

In my map, there are various features with IDs stored in an array called featureIds. Within my application, I have a button that can toggle the visibility of certain features. To address this toggling behavior, I am developing a JavaScript function named ...

Creating a test suite with Jasmine for an Angular ui-grid component compiled without using $scope

I have encountered an issue while using $compile to compile a ui-grid for Jasmine testing. Initially, everything worked smoothly when I passed $scope as a parameter to the controller. However, I am now transitioning to using vm, which has resulted in $comp ...

Encountered an error of 'npm ERR! invalid semver' when attempting to release an npm package

npm ERR! code EBADSEMVER npm ERR! invalid semver: npm ERR! Check out the full log of this run here: I attempted to reinstall node and semver, but unfortunately it did not resolve the issue. ...

Concealing and revealing content using JQuery based on user input in

I'm attempting to create a feature where the visibility of a password field is determined by the value of another input element. For instance, when the username is set to "admin", the password field should be hidden. If any other value is entered in ...

Step-by-step guide for sending data using module.exports in a node.js application

Currently, I am working on implementing a feature that will allow users to input data and store it in a database collection. The technologies I am using for this project are Node.js, MongoDB, Mongoose, Express.js, and AJAX. My goal is to capture user inpu ...

When a radio button is checked, add a class to its parent element that has a specific class assigned to it

In order to dynamically add a class to a specific div element higher up the DOM hierarchy when a radio button is clicked, I am in need of assistance. There are multiple instances of these div elements with different radio buttons, so it is crucial that on ...

What could be the reason for getting undefined when printing console.log(fibonacci(3))?

let array = [0, 1, 1]; const fibonacciSequence = (number) => { if (number < 2) { return array[number]; } else if (number == 2) { console.log(array.length-1); console.log((array[array.length-1])); // return (ar ...

What is the best way to replicate the functionality of AngularJS decorators in pure vanilla JavaScript (ES6)?

Using AngularJs Decorators offers a convenient method to enhance functions in services without altering the original service. How can a similar approach be implemented with javascript classes? In my current project, I have two libraries - one containing g ...

The Antd Tooltip becomes unresponsive when a component is clicked and moved

Having an issue with a button that has an Antd tooltip, here is the setup: <Tooltip title="Some text"> <button onClick={openNotes}><Icon icon="notes" /></button> </Tooltip> Upon clicking the button, the ...

What is the process for invoking a functional component within a class-based component using the onClick event?

I am trying to display my functional component in a class-based component, but it is not working as expected. I have created a SimpleTable component which is function-based and displays a table with some values. However, I want to show this table only wh ...

What happens if I attempt to access an undefined value from a JSON array?

I've been attempting to nest a JSON array within another JSON array. I believe I have structured it correctly, but when I try to access the second array, it returns undefined. JSON example : var data = [ {"Items" : [ {"item1" : "item1 ...

Manipulate the css pseudo-element :after using jQuery's .siblings() method

How can I use jQuery to edit the :after element created by CSS? <div class="box"> <h3 class="social">Social</h3> <ul> <li><a href="https://www.youtube.com/" onmou ...

Can this functionality be accomplished using only HTML and CSS, without relying on JavaScript?

Image for the Question Is it possible to create a zoom functionality using only HTML and CSS, without relying on JavaScript? I need this feature for a specific project that doesn't support JavaScript. ...