What is the functionality of the reduce() higher-order function?

Here is the reduce() function implementation:

function reduce(array, combine, start) { 
    let current = start;
    for (let element of array) { 
        current = combine(current, element); 
    }
    return current;
}

Now, I am tackling this question:

Utilize the reduce method along with the concat method to "flatten" an array of arrays into a single array that comprises all the elements of the original arrays.

Below is the solution:

let arrays = [[1, 2, 3], [4,5], [6]]; 
console.log(arrays.reduce((flat, current) => flat.concat(current), []));
// → [1, 2, 3, 4, 5, 6]

However, upon trying:

let arrays = [[1, 2, 3], [4, [79],5], [6]];
console.log(arrays.reduce((flat, current) => flat.concat(current), []));

The result is:

[1, 2, 3, 4, [79], 5, 6]

This indicates that the solution only handles flattening up to two nested arrays. But how does it work for arrays like [[1, 2, 3], [4,5], [6]]?

Considering the for loop in the reduce() function:

array = [1,4,6,[6,7],7,6,8,6];
for(element of array) 
   console.log(element);

// 146[6,7]7686 

The for loop does not fetch values from nested arrays. How does the first solution work then, and how can we write a solution that works for any number of nested arrays using recursion?

Answer №1

What is the reason behind the restriction on flattening arrays to only one level deep?

let arrays = [[1, 2, 3], [4, [79],5], [6]];console.log(arrays.reduce((flat, current) => flat.concat(current), []))

The limitation exists because the reduce function cannot differentiate between concatenating a primitive value (such as a number) and concatenating an array. When two arrays are concatenated using reduce, it results in a single array, without consideration for the individual elements being numbers or arrays.

To overcome this limitation, recursion can be used:

 function flatten(arrayToFlatten){
      return arrayToFlatten.reduce((prev, next)=>{
        if(!Array.isArray(next)){ // Base case, when a number is encountered
           return prev.concat(next);
        } else { // Recursive case, when an array is encountered
           return prev.concat(flatten(next));
        }
      }, []);
    }

Answer №2

Here is a code snippet that demonstrates how to flatten nested arrays:

const arrays = [[1, 2, 3],[4, [79], 5],[6]];
const flattenArray = array => array.reduce((acc, curr) => acc.concat(Array.isArray(curr) ? flattenArray(curr) : curr), []);
const result = flattenArray(arrays);

console.log(result);

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

"Implementing jQuery to dynamically set the href attribute for a link when

My website features a tabbed menu that displays content from various WordPress categories including Cars, Trucks, and Buses. The active tab is randomly selected each time the page is reloaded. However, there seems to be an issue with the "View More" button ...

Retrieve nested JSON data from an AJAX request

Currently, I am working with an API that provides JSON data back to me. The challenge I'm facing is figuring out how to access this data and showcase it on my HTML webpage since the results are stored in server memory rather than a file. Below is an e ...

Creating a unique-looking visual representation of progress with arcs

Looking to create a circular progress bar (see image below), with loading starting from the left bottom side up to the right bottom side. The empty state should be light-blue (#E8F6FD) and the progress color strong blue (#1CADEB). https://i.sstatic.net/VZ ...

Formatting code within an HTML document

I am attempting to customize a stock widget that I obtained from financialcontent.com. My current approach involves using Bootstrap for styling purposes. To incorporate the widget into a div, I found it necessary to embed the script directly within the HT ...

Is it possible for PHP to use the set cookie function to replace the cookie value set by JQuery cookie?

I'm facing an issue where I want a single cookie to be set and its value updated by PHP when a user logs in. However, currently it seems to just create a new separate cookie each time. Below is the code snippet where I am trying to set the cookie valu ...

Resource file for locating the mappings

As a beginner in sourcemapping, I have been tasked with saving the sourcemap in an external file. However, up to this point, I have only been able to concatenate the sourcemap to the minified .js file. What changes should I make to my approach? Am I miss ...

Find keys in an array based on a specified value

I need to retrieve an array of keys from an object that match a specified value ...

Populate a secondary dropdown menu using the selection from a primary dropdown menu and retrieve the corresponding "value" instead of displaying the value as a dropdown option

I am attempting to create two dropdowns that are populated by another dropdown. Below is the code: HTML: <form type=get action="action.php"> <select name="meal" id="meal" onChange="changecat(this.value);"> <option value="" disabled select ...

Is there a way to showcase the content of a text file in a sequential manner using Javascript/AJAX?

I am attempting to retrieve text data from a server file and exhibit it within a specific division on my website. Check out the AJAX/Javascript code I have been working with: <body onload="loadXMLDoc()"> <script> function loadX ...

Unveil concealed information within a freshly enlarged container

As I organize my content into an FAQ format, I want users to be able to click on a link and expand the section to reveal a list of items that can also be expanded individually. My goal is to have certain list items expand automatically when the FAQ section ...

Learn how to iterate over a JSON object using TypeScript in Angular5 to generate an array of objects

Here is a sample JSON code that includes an array "Customers" with objects and arrays nested inside: This is my JSON code snippet: { "Customers": [ { "customerData": { "secondLastName": "Apale", "firstLastName": "Lara", ...

Interacting Shadows with BufferGeometry in react-three-fiber

I've been working on my custom bufferGeometry in react-three-fiber, but I can't seem to get any shadows to show up. All the vertices, normals, and UVs are set correctly in my bufferGeometry, and I even tried adding indices to faces, but that just ...

Adjust the JavaScript variable upon pressing the "c" key

I'm trying to figure out how I can toggle the value of variable x in JavaScript when the key "c" is pressed. Specifically, I want x to change from 0 to 1 when "c" is pressed and revert back to 0 when it's released. I have already defined and name ...

Split vue.js templates into individual files

Is there a way to modify this code in Vue.js to achieve the following: <template type="login" /> <template type="subscribe" /> <template id="login"> <label>Username</label> <input placeholder="Enter your username" ke ...

Exploring the depths of time travel in Redux without the aid of developer

Has anyone successfully achieved time traveling capabilities with Redux core? It seems that this feature is limited to the devtools and not advised for production use. I had planned on implementing Redux in a multiplayer game to assist with managing clie ...

The XMLHttpRequest response states that the preflight request did not meet the access control check requirements

I am attempting to subscribe to a firebase cloud messaging topic by sending an http post request. var data = null; var xhr = new XMLHttpRequest(); xhr.withCredentials = true; xhr.addEventListener("readystatechange", function () { if (this.readyState ...

awaitMessages feature does not capture slash commands

In my development process, I have a file named botReady.js that is designed to run as soon as the bot becomes ready. In this file, there is a specific section dedicated to handling a bump bot in a designated channel obtained using the client.channels.fetch ...

Using Jest or Mocha alongside Vue: Uncaught SyntaxError: Cannot use import statement outside a module

Update: This post has undergone multiple edits, please refer to this new Stackoverflow post for a clearer explanation of the issue: SyntaxError: Cannot use import statement outside a module when following vue-test-utils official tutorial I have been searc ...

Vibrant progress bar design with CSS

Could someone assist me in coding a multicolor progress bar? I would like it to display red when the progress is less than 50, green when the progress is between 50 and 90, and blue when the progress is between 90 and 100. How can I achieve this? ...

Implementing the sticky positioning property to keep a div container fixed at the bottom of the page

As Bootstrap 4 no longer supports .affix, I had to look for an alternative solution to keep a box fixed. I needed a div container to remain fixed as you scroll to it. My current workaround is using: .fixedcard{ position: sticky; top:75%; } However, th ...