Ways to enhance code efficiency by utilizing reduce over multiple loops

I attempted to enhance the code by using reduce:

private getAllRegistryObjects(registry: RegistryGeneric) {
    const registryLayerItemGeneric = [];
    registry.RegistryLayers.forEach((layer) => {
        layer.items.forEach((item) => {
            registryLayerItemGeneric.push(item);
        });
    });

    return registryLayerItemGeneric;
}

Instead, I have tried this:

return registry.RegistryLayers.reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue.concat(currentValue.items.flat());
}, [])

However, it resulted in an empty array being returned.

Answer №1

Great job, your code is working perfectly:

var registry = {RegistryLayers: [
{ items: ['some', 'item'] },
{ items: ['other', 'things'] }
]};
var res = registry.RegistryLayers.reduce(function(previousValue, currentValue, currentIndex, array) {
  return previousValue.concat(currentValue.items.flat());
}, []);
console.log(res)

It returns:

['some', 'thing', 'other', 'things']

If you want to avoid repeatedly extending or copying the array during the reduce process, you can simplify it by using flatMap instead:

return registry.RegisteryLayers.flatMap((x) => x.items.flat());

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

Remove the </div> text and replace it with nothing

I'm attempting to substitute the end tag div with an empty string. Here is my code: $('#textDiv').html().replace(/'</div>'/g,'').replace(/<div>/g,'\n') This is the HTML: <div id='tex ...

Using Express, Node, and Angular to transmit audio files to the frontend

I am currently working on serving audio files from a Node/Express backend to an Angular frontend. On the server side, the code looks like this: var file = "/filepath.wav"; res.download(file, 'testAudio.wav'); And here's the client side c ...

Capturing Shadows in three.js: Unveiling the Magic of Shadows on Transparent Materials

Is there a way to create a shadow on a boxMesh without making the mesh itself visible? I came across a technique mentioned on the three.js GitHub Issue Tracker that used to work but no longer does - it required the usage of a custom shader. Are there any ...

React to every message in a Discord channel using Discord.js

I am in the process of developing a bot that will respond with either a thumbs up or thumbs down emoji to every message posted in a designated channel. Despite watching numerous tutorials on platforms like YouTube and Google, I have been unsuccessful in g ...

Tips on how to collapse all elements whenever one is being opened in a FAQ card using ReactJS

Clicking on a question reveals its text, and clicking on another collapses the previous one. The issue arises when trying to close an open question by clicking on it again - it doesn't work as intended due to a potential error in the If statement [im ...

Enhancing the appearance of the dragged object using HTML 5 Drag And Drop API

We are currently utilizing the HTML 5 Drag and Drop API in a project. Refer to this link for more information Everything is functioning smoothly so far, but we now require distinct styles for the original item source and the dragged item. The issue we&a ...

Creating a stunning star using three.js, just like the mesmerizing 100,000 stars in Chrome Experiments

I'm hoping I've found the right place this time. I'm currently trying to understand how to create a star using three.js similar to the way it was done in the chrome experiments 100,000 stars project. Although I looked into the source code, i ...

Ways to resolve the issue of setAttribute value not appearing on the UI

When using the setAttribute method to set a value in the DOM, why is it not being displayed in the user interface? https://i.sstatic.net/hZRgX.png ...

Adjusting Iframe Dimensions Dynamically with Javascript based on Anchor Location

I am experienced with handling this issue in flash, but I am struggling to figure out how to do it using Javascript and CSS. The problem involves an iframe that does not have an overflow property, and I need to modify its width/height. Is there a simple ...

Creating a paginated table with Nextjs, Prisma, and SWR: A step-by-step guide

I am attempting to set up a paginated table utilizing Nextjs, Prisma, and SWR. The table will display a list of invoices sorted by their ID. Here is an example of what it would look like: https://i.sstatic.net/WymoH.png To fetch all the data to the api r ...

Dealing with the issue of incompatible types in TypeScript with Vue 3 and Vuetify: How to handle numbers that are not assignable to type Readonly<any

Currently, I am utilizing Vite 3 along with Vue 3 and Vuetify 3 (including the Volar extension and ESLint). Additionally, I am incorporating the composition API in script setup mode. Within my HTML code, I am utilizing Vuetify's v-select. Unfortunate ...

Guide to incorporating a jade file into a node.js application after executing an Ajax request

While working on my node.js application, I encountered an issue with loading a new HTML file using Ajax on a button click. Despite everything else working perfectly, the new HTML file was not being loaded. This is how I am making the ajax call in my main. ...

Is the function for identifying the polygon in which a coordinate is located not functioning correctly?

Seeking a function to identify which polygons a coordinate falls within? Check out this function in the GitHub project: https://github.com/mikolalysenko/robust-point-in-polygon. Testing the function with the provided syntax gives the correct result (retur ...

JavaScript: change array objects into a string separated by dots

Task: Converting Nested Objects in an Array to Dot Notation String Using JavaScript Here is a sample data structure that needs to be converted: [ { property: 'name', children: [], message: 'name should not be empty', } ...

Determine the elapsed time in seconds between two specified moments

I am trying to implement two input fields in my HTML, one for a starting point and another for an end point. The user will enter two times like this: For example: [8:15] - [14:30] alert("XXXXX seconds") I want to calculate the number of seconds between 8 ...

Having trouble with jQuery's getJSON function throwing an error?

I have been working on a project where I am using the getJSON function to fetch JSON data from an API that I am developing. However, I am facing an issue where the getJSON function always triggers the error handler. Below is the JavaScript code I am using: ...

JavaScript Array Objects

As a newcomer to the world of Javascript, I've decided to take on the challenge of creating a blackjack game. Utilizing arrays and objects for my game: card = {}, //each card is represented as an object with suit, number, and points properties playe ...

Inconsistencies in Executing JavaScript Methods Between Mobile Safari and Android Chrome

I have a JavaScript method that appears like this: function onAction() { getValue1(); getValue2(); getValue3(); } When I invoke onAction(), I notice a discrepancy in behavior between Mobile Safari and Android Chrome. In Safari, all three meth ...

Refresh the Document Object Model (DOM) and transmit the present time

I am having an issue with sending the actual current time when a button is clicked. Instead of getting the current time, I am receiving the time when the page initially loaded. This button is used to submit a form on Google Sheets using an API. This is th ...

Transferring data to a child component through Route parameters

Although I have come across numerous questions and answers related to my query, I still seem unable to implement the solutions correctly. Every time I try, I end up with an 'undefined' error in my props. Let's take a look at my parent compo ...