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

Troubleshooting Bootstrap select box design discrepancies

Currently revamping a website and encountered an unusual issue with select boxes. There seems to be an overlapping white space where the option values should be. Here's a visual reference: View Image of Select Box Issue Utilizing Bootstrap for the re ...

Understanding ExpressJS: Exploring the distinctions between ?, +, * in string patterns and regular expressions

Hello there! As a newcomer to Express, I've been on the hunt for a thorough explanation of string patterns with no luck. The path-to-regexp documentation has left me scratching my head. In particular, I'm grappling with this somewhat enigmatic s ...

Exploring the capabilities of NEXTJS for retrieving data from the server

When trying to retrieve data from the nextjs server on the front end, there is an issue with the code following the fetch() function inside the onSubmit() function. Check out the /test page for more details. pages/test const onSubmit = (data) => { ...

Struggling to find the definition of a Typescript decorator after importing it from a separate file

Consider the following scenario: decorator.ts export function logStuff(target: Object, key: string | symbol, descriptor: TypedPropertyDescriptor<any>) { return { value: function (...args: any[]) { args.push("Another argument ...

Issue encountered in IE9 and IE10 when loading the angular library results in the "SCRIPT5007: Object expected" error for Angular JS

I am currently working on an AngularJS application that needs to be compatible with Firefox, IE 9, and IE 10. We are using the latest version of the AngularJS library (currently at 1.3.15). Our serverside is based on Java in the JavaEE platform, running on ...

Maintain the modifications in NPM software dependencies

Currently, I am developing a REACT web application and have integrated the react-datasheet library using NPM. To ensure compatibility with IE11, I made modifications to the JavaScript file installed via NPM. While these changes work perfectly on my local m ...

Refresh a div with Ajax once all data has been fully loaded

I am currently using an ajax refresh div function that reloads a specific div every 10 seconds. Occasionally, the div loads before receiving data from mysql. Is there a way to modify it so that it waits 2 seconds after reloading the div? <script type ...

What is the best way to include message body in CDATA using strophe?

I have a task to create messages in a specific format by using the following code: $msg({to: 'user', from: 'me', type: 'chat'}).c("body").t('some data'); This code generates the message structure as follows: <m ...

Is there a way to link Dom $(this) from a different function?

Could you please review this code and advise on how I can bind $(this) in an external function within a DOM event? $(".adder").on("click", function(){ updateText(); }); function updateText(){ $(this).next(".mapper").html("Got You!"); } <scrip ...

Can you suggest a method using Lodash to remove specific rows from an array based on the value of a certain field within the array?

Currently, I am utilizing the following function: remove: function (arr, property, num) { for (var i in arr) { if (arr[i][property] == num) arr.splice(i, 1); } }, Although this functi ...

Steps for Integrating a Web Service Reference in NodeJS

Can a Web reference be added to a NodeJS project similar to how it's done in .NET framework Web API Projects? Essentially, the NodeJS API project will serve as a middleware between the Front End and an XML Web service. The XML Web service is a secure ...

What is the reason behind the length property belonging to an array object?

While there are other instances, let's focus on the length property for now. Why does it appear as if we're copying it here: [].hasOwnProperty("length") //==> true It is common knowledge that an array's length property belongs ...

What is the correct method for configuring access permissions?

I'm in the process of developing a user management system, but I keep finding myself having to check the user type for each router. router.get('/admin/settings', (req, res) => { if(admin) { //Proceed. } } router.get(&apo ...

Exploring the depths of async/await within ExpressJS fetch operations

So far, my API-middleware code is functioning properly. I am being cautious to avoid any blocking calls in my express server, which is why I have implemented a function containing asynchronous fetch calls. I'm wondering if this extra step is necessar ...

Creating a multi-tiered cascading menu in a web form: Harnessing the power of

In my form, there is a field called 'Protein Change' that includes a multi-level dropdown. Currently, when a user selects an option from the dropdown (for example, CNV->Deletion), the selection should be shown in the field. However, this function ...

Stopping videos in the JQuery Cycle Plugin triggers the stop event

Currently, I have a simple cycle set up with YouTube videos using the following code: <script type="text/javascript"> $(document).ready(function () { $('#cycle').cycle({ fx: 'fade', sp ...

Avoiding the insertion of styles into the HEAD section when using Webpack MiniCssExtractPlugin in combination with Create React

Currently, I am utilizing create-react-app to develop a component library with Storybook JS. The ultimate goal is to release an NPM package containing these components for use in various projects. Within this library, SASS is employed, complete with global ...

Trouble displaying AngularJS $scope.data in the HTML code

I'm experiencing an issue where the data received from a POST request is being logged in the console, but is not displaying on the HTML page. Despite having a controller set up, the {{user}} variable is not appearing on the HTML page. While I can se ...

What is the best way to include two class names within a single div using Next.js?

Struggling to include two different CSS classes into a single div element, I encountered some issues. For reference, here is a screenshot: https://i.stack.imgur.com/UuCBV.png https://i.stack.imgur.com/sHNwq.png My code snippet looks like this: blog.js ...

Edit: "Submit a binary file with just JavaScript"

I am currently developing a Chrome application that utilizes the HTML5 Filesystem API to enable users to import and synchronize files. A challenge I'm facing is when attempting to sync image files, as they appear to become corrupted during the upload ...