I am currently working on completing my order book code, but I am struggling to understand how to summarize the objects

I have been working on my order book code and I am struggling to figure out how to summarize objects. Below is the current code that I have:

const orderbook = [
    {
        "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
        "Side": "BID",
        "Pair": "BTC/USDT",
        "Quantity": "20",
        "OriginalQuantity": "20",
        "Price": "23700",
        "Status": "pending",
        "Updated": 0,
        "time": 1677680878610,
        "id": 1
    },
    {
        "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
        "Side": "BID",
        "Pair": "BTC/USDT",
        "Quantity": "50",
        "OriginalQuantity": "50",
        "Price": "23674.52",
        "Status": "pending",
        "Updated": 0,
        "time": 1677681421267,
        "id": 2
    },
    {
        "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
        "Side": "BID",
        "Pair": "BTC/USDT",
        "Quantity": "50",
        "OriginalQuantity": "50",
        "Price": "23714.99",
        "Status": "pending",
        "Updated": 0,
        "time": 1677681888376,
        "id": 3
    },
    {
        "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
        "Side": "BID",
        "Pair": "BTC/USDT",
        "Quantity": "50",
        "OriginalQuantity": "50",
        "Price": "23674.52",
        "Status": "pending",
        "Updated": 0,
        "time": 1677681421267,
        "id": 2
    }
];

I am trying to merge objects with the same price. I need to write a function that takes one argument (the array above) and runs the following code:

Expected results:

const bidsOrders =
[
{Price: "23714.99", "Quantity": "50", orders: 1},
{Price: "23700", "Quantity": "20", orders: 1},
{Price: "23674.52", "Quantity": "100", orders: 2}
];

Answer №1

To fulfill this requirement, you can make use of the Array#reduce method.

Experience it live with this Demo:

const orderbook = [
  {
    "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
    "Side": "BID",
    "Pair": "BTC/USDT",
    "Quantity": "20",
    "OriginalQuantity": "20",
    "Price": "23700",
    "Status": "pending",
    "Updated": 0,
    "time": 1677680878610,
    "id": 1
  },
  {
    "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
    "Side": "BID",
    "Pair": "BTC/USDT",
    "Quantity": "50",
    "OriginalQuantity": "50",
    "Price": "23674.52",
    "Status": "pending",
    "Updated": 0,
    "time": 1677681421267,
    "id": 2
  },
  {
    "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
    "Side": "BID",
    "Pair": "BTC/USDT",
    "Quantity": "50",
    "OriginalQuantity": "50",
    "Price": "23714.99",
    "Status": "pending",
    "Updated": 0,
    "time": 1677681888376,
    "id": 3
  },
  {
    "ClientID": "31135d2c-a5f0-11ed-b07a-10e7c6f7c62e",
    "Side": "BID",
    "Pair": "BTC/USDT",
    "Quantity": "50",
    "OriginalQuantity": "50",
    "Price": "23674.52",
    "Status": "pending",
    "Updated": 0,
    "time": 1677681421267,
    "id": 2
  }
];

const res = orderbook.reduce((arr, curr) => {
  let itemIndex = arr.findIndex(item => item.Price === curr.Price);
  if(itemIndex !== -1) {
    arr[itemIndex] = {
        Price: curr.Price,
      Quantity: parseInt(arr[itemIndex].Quantity) + parseInt(curr.Quantity),
      orders: (arr[itemIndex].orders || 1) + 1
    }
  } else {
    arr = arr.concat({
        Price: curr.Price,
      Quantity: parseInt(curr.Quantity),
      orders: 1
    })
  }
  return arr
}, []);

console.log(res);

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

Nested setInterval in JavaScript refers to the practice of nesting

I am attempting to create nested timed code using setInterval. However, my initial approach does not produce any response from Chrome and Firefox: setInterval(function() { console.log('1'); setInterval(function(){ console.log(& ...

How can I anchor a div Banner saying "Get 50% off our products" to the Navbar directly above it?

Bootstrap Question: How can I attach the div Banner ("50% off of our products") to the Navbar directly above it? The structure looks like this: <Navbar> </Navbar> <div> <span>Discount: 50% off of our products </span </di ...

Are there any cross-platform inter-process communication APIs available in both C++ and Javascript?

In the process of developing an app, I am faced with the challenge of passing messages between a C++ application and a Javascript web app. While I have experience writing sockets code in both languages when required, I am now looking for a higher-level me ...

`methods that exhibit peculiar behaviors`

My routes are set up with the get method. app.get("/info/teachers", controller1); app.get("/info/teachers/:teacherid", controller2); app.get("/info/students", controller3); app.get("/info/students/:studentid", contr ...

What is the method in JavaScript for a child function to trigger a Return statement in its parent function?

I have encountered a unique problem. I need to retrieve some data downloaded via ajax and return it, but neither async nor sync modes are fetching the data in time for the return. Is there a way to call the return from a child function to the parent func ...

Unable to Click on Selenium Element

When a link is clicked on a website, the URL remains unchanged but a popup appears on the screen containing elements that can only be accessed after running driver.switchTo().defaultContent(). To access these elements, I have used a javascript executor com ...

Conceal a section if the array is not defined

Hey there, I've got this piece of code for checking the status of a Twitch streamer. $(document).ready(function () { // some initializations here var login = ''; var twitchStatusLinks = $('.twitch-status'); var twitchStatus ...

Tips on retrieving PHP variable values along with HTML response using AJAX in PHP

I am looking to retrieve 2 variables: 1) The total number of records from the mysqli query performed in search_members.php 2) A boolean value indicating whether any results were found Below is the code I have written: <input type="button" value="Sea ...

I'm having trouble applying CSS stylings to my components in my React project. What could be the issue causing this?

As a React beginner, I am facing issues with getting my CSS to work properly in my project. I know that CSS is not used directly in React, but rather interpreted as JavaScript using webpack and babel. What have I tried? I attempted to make changes to my w ...

How can we ensure that Protractor's ElementArrayFinder 'each' function pauses until the current action has finished before moving on to the next iteration?

Currently, I am facing an issue while trying to utilize an 'each' loop in my Angular 8 app's end-to-end tests using protractor. Within my page object, I have created a method that returns an ElementArrayFinder. public getCards(): ElementArr ...

Issues with jQuery autocomplete when using special characters (Norwegian)

On my website in Norway, I am facing an issue with jQuery's autocomplete function. When users type in the Norwegian characters æ, ø, and å, the autocomplete feature suggests words with these characters within them but not ones that start with these ...

What is the best way to determine if a property exclusively belongs to the child class or its subclass in Javascript?

I am currently working on a project in Javascript where I need to retrieve properties that are only present in a subclass (child class) and not in the parent class. Despite using .hasOwnProperty(), I have run into an issue where it also returns true for th ...

What is the most efficient way to substitute text within an HTML document?

Is there a way to switch between languages on a website to replace text on multiple pages with a simple button click? What is the most efficient method for achieving this? This code snippet only changes text in the first div. Is there a way to implement a ...

Modifying button appearance based on state change in AngularJS

I have a button with a grey color and I want to create two different states for it: one that is selected (blue) and another that is in an idle state (grey). Currently, I am working on Angularjs but I am fairly new to this platform. Could you kindly provid ...

Encountered a SyntaxError: Unexpected token "e" while attempting to parse a JSON string

When I attempt to use JSON.parse in order to convert the string below into a JavaScript object, I encounter an "Uncaught SyntaxError: Unexpected token e" error. { "__type": "HRIS.oHRData, HRIES, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ...

Combining audio and video streams in Node.js

I'm currently developing a YouTube video downloader using the ytdl-core library. However, I've encountered an issue where it cannot fetch high quality videos with audio because they are stored in separate files on YouTube. My goal is to download ...

Working with Vue.js to call component methods when the page loads

My payment implementation utilizes vue-js and stripe. I found that the only way to incorporate Stripe with vue-js was through the use of script.onload. Now, I am trying to access some of my methods within the onload function. Specifically, I want to call ...

Tips for crafting paragraphs that double as sieves

I'm trying to simplify and shorten this code. I have three HTML paragraphs acting as filters: "all", "positive," and "negative", referring to reviews. Each has a corresponding div for reviews: "allcont", "poscont", and "negcont". Clicking on any of th ...

Discontinue playing videos embedded in iframes on Dailymotion

I'm currently working on creating a slider that includes videos from multiple providers, and I need to ensure that the videos stop when changing slides. So far, I've successfully implemented this feature for Vimeo and YouTube without making any a ...