Iterating through an array of objects and performing reduction based on various key-value pairs

I am faced with a challenge of consolidating a large array of objects into one single array that has a specific structure. Each item, such as a banana, needs to be present in two separate objects for buy orders and sell orders, each with their own distinct price and data.

I attempted to identify the unique pairings of items (banana, apple, orange, etc.) and loop through them, while also nesting another map function for the data processing, but I have not been able to find a solution yet.

let uniquePairing = Array.from([...new Set(data.map(item => item["name"]))])


**let data = [{
name:'banana,
price:( average cost)
type:buy
items: ( total bananas)
fee: ( total fees)
},
{
name:'banana,
price:( average cost)
type:sell
items: ( total bananas)
fee: ( total fees)
},
{ apples...
]**

Example of data

let data = [
{
name:"banana",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:2,
type: "sell",
fee: 0.5,
items:25
},
{
name:"apple",
price:1,
type: "buy"
fee: 0.5
items:25
},
{
name:"apple",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:2,
type: "sell",
fee: 0.5,
items:25
}
]

Answer №1

It seems like you're looking for a solution using the reduce function:

const uniqueItems = data.reduce((accumulator, currentItem) => {
  const name = currentItem.name,
        type = currentItem.type;

  let matchedItem = accumulator.find(item => item.name === name && item.type === type);
  
  if (!matchedItem) {
    accumulator.push({
      ...currentItem,
      totalPrice: currentItem.price,
      objCount: 1
    });
  } else {
    matchedItem.totalPrice += currentItem.price;
    matchedItem.objCount++;
    matchedItem.price = matchedItem.totalPrice / matchedItem.objCount;
    matchedItem.items += currentItem.items;
    matchedItem.fee += currentItem.fee;
  }

  return accumulator;
}, []);

Answer №2

One way to achieve this is by following the steps below:

   let collection = [
{
name:"banana",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"banana",
price:2,
type: "sell",
fee: 0.5,
items:25
},
{
name:"apple",
price:1,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:1.2,
type: "buy",
fee: 0.5,
items:25
},
{
name:"apple",
price:2,
type: "sell",
fee: 0.5,
items:25
}
]

const getFruitDetails = (fruits, fruit) => fruits.filter(fr=> fr.name===fruit.name && fr.type=== fruit.type)

const calculateTotal = (fruits, field) => fruits.reduce((acc,cur)=> acc+=cur[field], 0)

const checkIfRegistered = (fruits, value) => fruits.some(fruit=> fruit.type === value.type && fruit.name===value.name)

const extractFruits = (fruits) => {
  return fruits.reduce((acc, cur)=> {
if(checkIfRegistered(acc, cur)){
  return acc
}
acc.push({name: cur.name, type: cur.type})
return acc
  }, [])
}

function mergeCollection(arr){
  const fruits = extractFruits(arr)
  return fruits.map(fruit=> {
const data = getFruitDetails(arr, fruit)
return {
  name: fruit.name,
  price: calculateTotal(data, "price"),
  type: fruit.type,
  fee: calculateTotal(data, "fee"),
  items: calculateTotal(data, "items")
}
  })
}

console.log(mergeCollection(collection))

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

The $q.all() function in angular seems to struggle with resolving properly

Having trouble with 3 $http calls in a factory. Creating 4 promises: var promise = $q.defer(), PBdeferred = $q.defer(), Rdeferred = $q.defer(), Pdeferred = $q.defer(); Making the first call to the API: $http.get('/pendingBills').then(fu ...

Customize the element of the root node of a MUI component using the styled()

I am trying to implement the "component" prop with a MUI component (such as ListItem) using the styled() API. However, I am facing an issue where it says that "component" is not a valid prop. Can someone guide me on how to correctly achieve this? I have se ...

What steps do I need to take in Bootstrap 5 to add a search icon to the navbar that reveals a search box beneath it when clicked?

I've made progress on the navbar design Now, I'm looking to add a search icon next to the login button. Clicking on the search icon should reveal a search box below the navbar, similar to the image shown below. My transparent navbar has a relati ...

Prevent duplicating ReactJs when using Gulp: A guide

My current project involves using ReactJS as the view library for client-side rendering. Additionally, I am utilizing a lot of components from Material-UI in my application. One challenge that I have encountered is the need to use gulp for setting up brows ...

Rendering HTML with jQuery using AJAX: Step-by-step guide

Within my webpage, I have implemented a select box that contains a list of various books. The purpose of this select box is to allow the user to choose a book and then click a submit button in order to view the chapters of that book on a separate page. Ho ...

A variety of personalized Vimeo play buttons

Recently, I stumbled upon a genius solution by Chris Coyier for creating custom Vimeo play buttons. It worked perfectly for my needs, but now I'm facing a challenge - how to make it function with multiple videos on the same page. I tried swapping out ...

`Generate JSON list`

How can I properly encode an array in PHP as JSON, ensuring it includes two variables? $var = 33; $last = 44; Here are the database results: foreach($query->result() as $r) { $data[]= $r; // Fills the array with results } I am attempting to cre ...

Move the page to the beginning of the vertical stepper upon clicking the "next" button

I am currently working on optimizing a lengthy form to enhance user experience. To illustrate my point, I have come across a simplified example of the code I am dealing with which can be found here. My primary goal is to ensure that when a user proceeds t ...

The function .load callback was triggered on five separate occasions

I'm currently working with the code below and I have a feeling that I'm overlooking something important but just can't seem to figure it out. Basically, when the user clicks a button, a fragment of the page is loaded. Once this loading is s ...

Optimal approach for integrating enum with Angular, Mongoose, and Node.js

When it comes to fetching values from MongoDB and displaying them with AngularJS, the process can be straightforward with Jade but becomes more complex with Angular. Here is how the data flows: An array of items is retrieved from MongoDB, each containin ...

When using Node.js, you may encounter the error message: "TypeError: brevo.ApiClient is not a constructor

My goal is to set up an automatic email sending system that, upon receiving details like name and email, will send a confirmation email to the provided email address with the message "subscribed." I've been working on this task for about 7 hours strai ...

Learn how to use canvas and JavaScript to draw lines that display x and y coordinates on top of the mouse pointer at the same time

Implement a functionality in which lines are drawn while the mouse button is held down and simultaneously display x & y coordinates on top of the mouse pointer during mouse movement using canvas and JavaScript. The issue arises when attempting to draw lin ...

This error occurs when trying to assign a value to a property of a variable that is currently undefined

Having some issues with assigning the latitude and longitude values to a variable in my code. I am able to retrieve them correctly, but when trying to use them in another method (onUpload()), I am facing some errors. export class latlonComponent implement ...

Testing a cucumber scenario by comparing the redirect URL with a different URL

Currently, I am working on writing Cucumber tests for my project. One issue I have encountered is that when clicking a certain button in my code, it redirects to another page with a fixed URL. How can I retrieve the current URL within the Cucumber test? I ...

Locate a specific sequence of characters within an array of objects using JavaScript

I am working with an array of objects, where each object contains a string value. My task is to search for a specific substring within the string. [ { "link": "https://www.sec.gov/Archives/edgar/data/1702510/000170251022000084/00 ...

Tips for locating the ID of an object in an array when only one attribute in the "child" array is known

Seeking assistance in creating a JavaScript function that efficiently determines the id of the "parent" object based on the code of a "child" object from the dataArray. For example: getIdParent("240#code") -> should return "1" [ { id: 0, ...

What causes the "node: bad option" error to occur when I include a custom flag in the nodejs command line within an Angular 9 application?

Seeking assistance with adding a custom flag to the npm start command in an Angular 9 project. The goal is to intercept proxy requests within the local server and manipulate data. However, encountering the "node: bad option" error consistently. Looking for ...

Show the user's name in an Express partial once they have logged in

I've been trying to find a solution for my issue without success. Here's the scenario: I have a homepage ('/'), a profile page ('/profile'), and a login/register page. I'm using passport with local, twitter, and google fo ...

VueJS - Validating Props with Objects

What is the best way to validate Object type props in VueJS to guarantee that certain fields are defined within the object? For instance, I need to make sure that the user prop includes 'name', 'birthDate', and other specific fields. ...

What is the most effective method for obtaining only the "steamid" from an AJAX request (or any other method)?

I have been attempting to extract only the "steamid" from an AJAX link without success. Could someone please provide some assistance? Here is the link to find and retrieve only the "steamid": here This is the code I have tried: var xhttp = new XMLHt ...