Can we find a different way to address this issue with a "functional programming" mindset that doesn't involve utilizing the `forEach` method?

There has been a discussion about whether or not we still need to use forEach in JavaScript due to the availability of new language features. Some have suggested that this shift is an indirect push towards functional programming. I recently came across an array manipulation problem that required nested forEach loops and I started thinking if there is a more functional way to solve it. While I was able to rewrite the code using reduce, it turned out to be longer than the original forEach solution. This made me question if there's a better approach to using functional programming to tackle this problem.

The challenge at hand is to transform an array of arrays into a flat array where each element is paired with the number of the sub-array it originated from. For example, convert [[8,2,4],[5],[1,7]] into

[[8,0],[2,0],[4,0],[5,1],[1,2],[7,2]]
.

(To provide context for some of the initial comments on this question, the original emphasis was on reducing the code length. However, my real aim was to explore alternative solutions to this problem, which led to the revised question above.)

const oldArr = [[8,2,4],[5],[1,7]];

const newArr1 = [];
oldArr.forEach((subArr, subArrNum) => {
  subArr.forEach(elmt => {newArr1.push([elmt, subArrNum]);});
});

const newArr2 = oldArr.reduce((accum1, subArr, subArrNum) => accum1.concat(
  subArr.reduce((accum2, elmt) => accum2.concat([[elmt, subArrNum]]), [])
), []);

console.log(JSON.stringify(newArr1));
console.log(JSON.stringify(newArr2));

// To compare code length, here are the same solutions using single letter variable names compressed onto one line:

const o = oldArr;
let x,y;

x=[];o.forEach((s,n)=>{s.forEach(e=>{x.push([e,n]);});});

y=o.reduce((a,s,n)=>a.concat(s.reduce((b,e)=>b.concat([[e,n]]),[])),[]);

console.log(JSON.stringify(x));
console.log(JSON.stringify(y));

Answer №1

When discussing the question, @Ryan shared a solution labeled as newArray1 in the code snippet below, while @Potter provided an alternative labeled newArray2, intended to be "babel-safe" by making slight adjustments to variable names and parentheses:

const o = [[8,2,4],[5],[1,7]];

const newArray1 = [].concat      (   ...o.map((x,i)=>x.map(y=>[y,i])));
const newArray2 = [].concat.apply([],   o.map((x,i)=>x.map(y=>[y,i]));

console.log(JSON.stringify(newArray1));
console.log(JSON.stringify(newArray2));

In comparing the two solutions, I find that the reduced clutter in this approach makes it slightly easier to comprehend compared to my original functional solution.

It is worth noting that Ryan later commented on a potential issue with this method. He mentioned that [].concat(...x) (and likely its "babel-safe" variant) "...can cause a stack overflow, for one; try [].concat(...Array(1000000)). Ideally there would be a built-in function similar to

const concat = arrs => arrs.reduce((m, n) => m.concat(n), []);
(but possibly more efficient)."

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

Javascript: struggling with focus loss

Looking for a way to transform a navigation item into a search bar upon clicking, and revert back to its original state when the user clicks elsewhere. The morphing aspect is working correctly but I'm having trouble using 'blur' to trigger t ...

The onclick function fails to function properly following an Ajax reload of the <div> element

I have an issue with my onclick function that only works the first time. Every time the onclick function triggers an ajax request, it successfully reloads a div which contains code to retrieve values from SQL and build an HTML table using a for loop. Alth ...

Enhancing the templateUrl with additional value in AngularJS and PHP

I am having trouble capturing the value of the {fold} and adding it to the templateUrl. The php file show.person.php is returning an error because it is only recognizing 'id' as '{fold}' and not as a number like '54' In my co ...

JavaScript: Efficiently Sorting a Multidimensional Array

Here is the array that needs to be sorted based on the third item: const array = [ [1, "Convention Hall", "Mumbai", 10, "XYZ Company"], [2, "Auditorium", "Delhi", 10, "ABC Company"], [3, "CenterHall", "Bangalore", 10, "ZZZ Company"], ... ...

Data will not bind with Laravel and Vue

I am currently working on a Laravel project and trying to develop a basic editing feature for posts. My approach involves using Vue.js 2 to bind the data, but unfortunately, I am facing issues with displaying it - I'm not quite sure what's causin ...

Contrast between using "export { something }" and "export something" in JavaScript modules

Can you explain the difference between the following code snippets: import something from "../something"; export { something }; vs import something from "../something"; export something; I noticed in the react-is package from react, there is an export ...

Utilizing Input Data from One Component in Another - Angular4

As a newcomer to Angular, I'm facing an issue where I need to access a variable from ComponentA in ComponentB. Here's the code snippet that demonstrates what I'm trying to achieve (I want to utilize the "favoriteSeason" input result in the " ...

Encountering an error in React Native: Unable to access property 'length' as it is

Currently, I am working on developing a registration application and I have encountered some issues in the final phases when attempting to submit the new data to the server. Below is the script I am using: import React from 'react'; import React ...

Utilize jQuery to extract URL parameters and incorporate them into a script

I have a unique link: http://mywebsite.org/product/page?var_one=result1&var_two=result2&var_three=result3&var_four=result4 The values can vary, meaning the parameters are not fixed. My example includes 4 parameters, but there could be more ...

Formik Fields with unique key properties

When mapping text fields, I follow this structure: { AddVehicleFields.map(({formikRef, ...input}) => ( <> <TextField key={formikRef} helperText={ getIn(formik.touched, formikRef) ? getIn(formik. ...

Converting blobs to strings and vice versa in Javascript

After successfully converting a blob to a string using FileReader, the challenge now is to convert it back: var reader = new window.FileReader(); reader.readAsDataURL(blob); reader.onloadend = function() { base64data = reader.result; var blobToSend ...

The function iframe.scrollTo() is not effective for scrolling through Excel or PowerPoint documents on an iPad

I am trying to create a custom scrolling feature for iframe content specifically for iPad. Currently, I have set up my iframe like this: <div id="scroller" style="height: 300px; width: 100%; overflow: auto;"> <iframe height="100%" id="iframe" ...

The console is showing the Ajax Get request being logged, but for some reason it is not displaying on the

Could someone please explain why this response isn't displaying on the page? $.ajaxPrefilter( function (options) { if (options.crossDomain && jQuery.support.cors) { var http = (window.location.protocol === 'http:' ? &apos ...

Transitioning from jQuery to Prototype

After switching from a jQuery background to Prototype, I am curious if there is a chart available that shows the equivalent prototype methods for specific jQuery methods? To be more specific, I am searching for the equivalent of $('#my-id').prep ...

Typescript error encountered when executing multiple API calls in a loop causing Internal Server Error

I'm relatively new to Typescript/Javascript and I am working on a function called setBias(). In this function, I want to set all indices of this.articles[i].result equal to the biased rating returned by the function getBiasedRating(this.articles[i].ur ...

Switching Div Elements Created by PHP

Utilizing MySQL, I am fetching data to dynamically generate nested div tags in a hierarchical structure. This structure consists of div tags within div tags within div tags, all uniquely identified through PHP-generated ids: <div class="holder"> ...

Exploring Perl: Techniques for cycling through arrays within different objects and retrieving data from web services

Upon requesting a web service, I receive a JSON response: { "timestamp" : "2019-06-11T08:04:35Z", "version" : "0.5", "document" : [ { "href" : "http://opac.sub.uni-goettingen.de/DB=1/PPNSET?PPN=1629107239", "item" : [ ...

The collapsible section expands upon loading the page

Trying to implement Disqus as a plugin on my test webpage, I created a collapsible section with a "Show comments" button. The idea was to hide the plugin by default and reveal it only when users click on "Show comments". Despite using the w3schools example ...

Just a quick question about using AJAX

Before submitting my PHP page, I need to send an email. The mail script is in a file called sendmails.php. Is it possible to use JavaScript to send an AJAX request to send the email before submitting the page? Here is an example: function submit_page() { ...

Encountering an issue with finding the module `scheduler/tracing` in React Native

Encountering an error during the react-native run-android process: Error: Unable to resolve module `scheduler/tracing` from `/Users/miftahali/projects/react/appscustomec/node_modules/react-native/Libraries/Renderer/oss/ReactNativeRenderer-dev.js`: Module ...