Looking for assistance with utilizing nested array functions in JavaScript?

I have two JavaScript arrays containing objects:

const types = [
  {
    id: 1,
    name: 'Paint',
    unit: 'L',
  },
  {
    id: 2,
    name: 'Resin',
    unit: 'mL',
  },
  {
    id: 3,
    name: 'Fiberglass',
    unit: 'yd',
  }
];

const items = [
  {
    id: 1,
    type_id: 1,
    name: 'Brand x paint',

    qty: 5,
  },
  {
    id: 2,
    type_id: 1,
    name: 'Brand y paint',
    supplier: 'brand y',
    qty: 3,
  },
  {
    id: 3,
    type_id: 2,
    name: 'Brand x resin',
    qty: 5,
  },
  {
    id: 3,
    type_id: 2,
    name: 'Brand y resin',
    qty: 2,
  },
  {
    id: 3,
    type_id: 2,
    name: 'Brand z resin',
    qty: 3,
  },
  {
    id: 3,
    type_id: 2,
    name: 'Brand x fiberglass',
    qty: 7,
  },
  {
    id: 3,
    type_id: 2,
    name: 'Brand y fiberglass',
    qty: 9,
  },
];

I am attempting to add a new property called total_qty to each object in the types array. This property should represent the sum of quantities for each respective type from the items array. I tried using the map function and filtering the items array based on type_id, but it is not working as expected:

const itemTypes  =  types.map( (type) => {
    type.total_qty = items
      .filter((item) => item.type_id === type.id)
      .reduce((sum, item) => sum += item.qty, 0)
  }     
)

If there is a more efficient way to achieve this or if you have any suggestions to improve my current approach, I would greatly appreciate it. Thank you!

Answer ā„–1

The issue arises from the use of map without a return in its callback, causing the given array to be mutated. Consequently, map generates undefined values, while the types array is updated but not displayed.

A more efficient approach involves utilizing a Map to eliminate nested iterations, resulting in a time complexity of O(n) instead of O(nĀ²).

This method also refrains from altering the original type objects and instead creates new objects with an additional property within the newly formed array:

const types = [ { id: 1, name: 'Paint', unit: 'L', }, { id: 2, name: 'Resin', unit: 'mL', }, { id: 3, name: 'Fiberglass', unit: 'yd', } ]; 
const items = [ { id: 1, type_id: 1, name: 'Brand x paint', qty: 5, }, { id: 2, type_id: 1, name: 'Brand y paint', supplier: 'brand y', qty: 3, }, { id: 3, type_id: 2, name: 'Brand x resin', qty: 5, }, { id: 3, type_id: 2, name: 'Brand y resin', qty: 2, }, { id: 3, type_id: 2, name: 'Brand z resin', qty: 3, }, { id: 3, type_id: 2, name: 'Brand x fiberglass', qty: 7, }, { id: 3, type_id: 2, name: 'Brand y fiberglass', qty: 9, }, ];

// Utilize a Map keyed by type_id with the extended type object as the value 
// (initialized as 0)
const map = new Map(types.map( type => [type.id, {...type, total_qty: 0 }] ));
// Incorporate the item quantities into the appropriate map-value
items.forEach(item => map.get(item.type_id).total_qty += item.qty);
// Retrieve the map values
const itemTypes = Array.from(map.values());
console.log(itemTypes); 

Answer ā„–2

The initial value for the accumulator is missing in the code snippet that uses reduce.

const itemsType  =  types.map( (type) => {
     const temp = items;
     type.total_qty = temp
         .filter( item => item.type_id === type.id)
         .reduce( (acc, item) => acc + item.qty, 0); // The initial value should be provided here
  }     
)

Answer ā„–3

Instead of iterating through each item, a more efficient approach would be to build a lookup object with quantities by id :

const types = [ { id: 1, unit: 'L', name: 'Paint', }, { id: 2, unit: 'mL', name: 'Resin', }, { id: 3, unit: 'yd', name: 'Fiberglass', } ]; 

const items = [ { id: 1, type_id: 1, qty: 5, name: 'Brand x paint', }, { id: 2, type_id: 1, qty: 3, name: 'Brand y paint', supplier: 'brand y', }, { id: 3, type_id: 2, qty: 5, name: 'Brand x resin', }, { id: 3, type_id: 2, qty: 2, name: 'Brand y resin', }, { id: 3, type_id: 2, qty: 3, name: 'Brand z resin', }, { id: 3, type_id: 2, qty: 7, name: 'Brand x fiberglass', }, { id: 3, type_id: 2, qty: 9, name: 'Brand y fiberglass', }, ];

const qtys = items.reduce((obj, item) => 
                   (obj[item.type_id] = (obj[item.type_id] || 0) + item.qty, obj), {})

const itemTypes = types.map(type => ({ ...type, total_qty: qtys[type.id] }))

console.log( JSON.stringify( itemTypes ).replace(/},/g, '},\n ') )
console.log( qtys )

Learn more about spread syntax in object literals here : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax#Spread_in_object_literals

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

What is the best way to assign values to a dynamically allocated 2D array in C?

My goal is to create a 2D array and pass it as a pointer to a 2D array inside a function in C. I am attempting to use the braces syntax that initializes the values of elements in a 1D array, but I am unsure how to implement it with a multidimensional array ...

Guide on how to use Vue's watch feature to monitor a particular property within an array

I am interested in observing the "clientFilter" within an array TableProduit: [ { nr_commande: 0, date_creation: "", id_delegue: "1", clientFilter: "" } ], ...

Guide on expanding the capabilities of IterableIterator in TypeScript

I am currently working on extending the functionality of Iterable by adding a where method, similar to C#'s Enumerable.where(). While it is straightforward to extend the Array prototype, I am encountering difficulties in figuring out how to extend an ...

The document's event listener for the "click" event on the element with the ID of "myId" is unable to properly update the owl carousel

I have been experimenting with the Carousel example and modifying the function to enable loading on click. Here is my updated code snippet: $(document).on("click","#myId",function(){ $("#owl-demo").owlCarousel({ autoPlay : 3000, //Set AutoPlay ...

Using jQuery to retrieve values from clicked buttons

I'm trying to retrieve the values of a jQuery button upon form submission, but my current setup is not working. Specifically, I need to extract the value of data-url. Below is the code snippet I am using: $("#addAgency").submit(function(event) { ...

Implement Vue.js functionality to dynamically add the 'active' class upon clicking an element, while also removing

Is it possible to create an active link on a div element? Check out this example to see how you can achieve that in your code: http://jsfiddle.net/fiddleyetu/9ff79/ $(function() { $( 'ul.nav li' ).on( 'click', function() { $ ...

The problem with the first item title in the Jquery slider is causing

I've been working on setting up a Jquery slider (caroufredsel) in which I want certain elements to be displayed above the slider itself, outside of the wrapper. Everything is working fine except for the first slide! After spending several days trying ...

Is there a way to display an alert using JavaScript that only appears once per day?

I've created a website that displays an alert to the user upon logging in. Currently, the alert is shown each time the user logs in, but I'm looking to make it display only once per day at initial page loading. How can I achieve this? Below i ...

What is the most effective toArray transformation method to employ?

My code was recently suggested to be changed by IntelliJ, replacing: String[] normalizedNames = rawToNormalized.values().stream().toArray(String[]::new); with String[] normalizedAliases = rawToNormalized.values().toArray(new String[0]); In a post by A ...

What could be causing an error in my Vue app when attempting to process a payment using Google Pay on a mobile device, resulting in the message "Blocked a frame with origin

When implementing payment through Google Pay on Chrome desktop, it functions smoothly. However, an error occurs when attempting to pay using a smartphone, triggering an additional modal window with a card selection: vue.esm.js?a026:152 Uncaught (in promise ...

What is the best way to attach an event listener to detect the coordinates where a click occurs inside a div element?

Imagine a situation where you have a div container measuring 200px by 500px. The goal is to implement an event listener that can identify the x and y coordinates within this div when it is clicked. What would be the approach to achieve this in React? ...

Exploring the Process of Setting Up a Temporary Endpoint in Express

Currently, I am working with the node.js framework express and my goal is to establish a temporary endpoint. This can either be one that automatically deletes itself after being visited once, or one that I can manually remove later on. Any assistance wou ...

Interacting between Jquery and servlets using AJAX

In order to establish communication between a Jquery function and a servlet in Tomcat, I have created the following code snippets. Servlet Code: import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; i ...

Avoid triggering the Change event after selecting an option from the Autocomplete feature

In the scenario, a user has the option to input a value in two ways: By choosing an item from a list (retrieved as a json list from file.php). Or by manually typing it in (where we verify its existence with an ajax call to file2.php). If the value is con ...

Best practices for running Javascript based on PHP output

I'm trying to figure out how to add a PHP Exception to my JavaScript function that sends form data to a database. I want it to work like this: "if 'whatever' condition is met, execute the JavaScript function; otherwise, throw an Exception me ...

Is it possible to dynamically load JavaScript?

I'm currently working on a project that requires me to dynamically add JavaScript. I have a global.js file that contains all the global variables I need to add dynamically. However, I'm facing an issue where global.js is not being added before ut ...

Type in data into the database in real-time

Can someone help me with inserting data into a database while typing values in a textbox? My AJAX code doesn't seem to be working and I'm not getting any errors. Please assist me as soon as possible. Here is my AJAX code: var userid = '#u ...

Using JavaScript within SQL allows developers to combine the power

Every year, I need to insert a new primary key into my SQL database that follows a specific format (for example, in 2012 the key is 2012000000, and in 2013 the key is 2013000000). I want this process to happen automatically. My plan is to incorporate a sc ...

Updating React component props

After updating the state in a component and passing the new props into the child, I noticed that the child is not updating correctly and the defaultValue of the input is not changing. My initial thought was that using this.props could be the issue, so I sw ...

JQuery Ajax encounters a 500 error message due to an internal server issue

I'm currently using the jQuery library to send an ajax request to a PHP file. Initially, everything was working perfectly fine with a relative path like this: url:"fetch_term_grades.php", However, when I modified the path to be more specific like th ...