Identify the key in an array of objects that corresponds to the highest volume value, and return both the key and its

I am working with an array of objects that include a baseAsset key and Volume for each object, with the volume value varying between objects.

My goal is to find the object with the highest volume value based on a match with the baseAsset key. Efficiency and speed are crucial due to the large size of the array containing over 3000 objects

let tickerA = [{
    pair: 'AUDUSD',
    baseAsset: 'AUD',
    lastPriceUSD: 0.74,
    volume: 1000
}, {
    pair: 'AUDUSD',
    baseAsset: 'AUD',
    lastPriceUSD: 0.76,
    volume: 2000
}, {
    pair: 'USDEUR',
    baseAsset: 'USD',
    lastPriceUSD: 1.25,
    volume: 1200
}, {
    pair: 'USDEUR',
    baseAsset: 'USD',
    lastPriceUSD: 1.19,
    volume: 1500
}]

The expected result when running a function

tickerB = [{
    baseAsset: 'AUD',
    lastPriceUSD: 0.76,
    volume: 2000
}, {
    baseAsset: 'USD',
    lastPriceUSD: 1.25,
    volume: 1500
}]

Answer №1

To efficiently achieve this task in linear time complexity (O(n)), iterate through the list and store the largest item in an object. Once completed, the values will be accessible through the Object.values method of the specified groups:

const tickerA = [{pair: 'AUDUSD',baseAsset: 'AUD',lastPriceUSD: 0.74,volume: 1000}, {pair: 'AUDUSD',baseAsset: 'AUD',lastPriceUSD: 0.76,volume: 2000}, {pair: 'USDEUR',baseAsset: 'USD',lastPriceUSD: 1.25,volume: 1200}, {pair: 'USDEUR',baseAsset: 'USD',lastPriceUSD: 1.19,volume: 1500}]

const groups = tickerA.reduce((largest, {baseAsset, lastPriceUSD, volume}) => {
    /* 
     * Check if it's a new baseAsset or larger than the previous one, then update the group under the baseAsset key 
    */
    if (!largest[baseAsset] || largest[baseAsset]['volume'] < volume ) {
        largest[baseAsset] = {baseAsset, lastPriceUSD, volume}
    }

    return largest
}, {})

const TickerB = Object.values(groups);
console.log(TickerB);

Answer №2

To efficiently compare and select items, we can iterate through the values of tickerA and associate them with the corresponding baseAsset keys based on the condition that the volume value is higher than the current item's volume for that particular baseAsset key:

let tickerA = [{
    pair: 'AUDUSD',
    baseAsset: 'AUD',
    lastPriceUSD: 0.74,
    volume: 1000
}, {
    pair: 'AUDUSD',
    baseAsset: 'AUD',
    lastPriceUSD: 0.76,
    volume: 2000
}, {
    pair: 'USDEUR',
    baseAsset: 'USD',
    lastPriceUSD: 1.25,
    volume: 1200
}, {
    pair: 'USDEUR',
    baseAsset: 'USD',
    lastPriceUSD: 1.19,
    volume: 1500
}];

/* Initializing a map to store max volume values per baseAsset */
const map = new Map()

/* Iterating through tickerA items to identify highest volume per baseAsset class */
for(const item of tickerA) {
  
  const assetMatch = map.get(item.baseAsset);
  
  if(assetMatch && item.volume < assetMatch.volume) {
    /* Discarding current item if matching item (by asset) has greater volume */
    continue;
  }
  else {
    /* Updating map entry if this tickerA item represents first or has higher volume in its asset class */
    map.set(item.baseAsset, item);
  }  
}
 
/* Converting map values to an array */
const tickerB = Array.from(map.values());

console.log(tickerB);

Answer №3

This unique approach combines the baseAsset elements and then extracts the combined values at the end.

It operates with a time complexity of O(n).

let tickerA = [{pair: 'AUDUSD',baseAsset: 'AUD',lastPriceUSD: 0.74,volume: 1000}, {pair: 'AUDUSD',baseAsset: 'AUD',lastPriceUSD: 0.76,volume: 2000}, {pair: 'USDEUR',baseAsset: 'USD',lastPriceUSD: 1.25,volume: 1200}, {pair: 'USDEUR',baseAsset: 'USD',lastPriceUSD: 1.19,volume: 1500}];
let result = Object.values(tickerA.reduce((a, {baseAsset, lastPriceUSD, volume}) => {
    let {volume: current} = a[baseAsset] || {volume: Number.MAX_SAFE_INTEGER};
    
    if (current < volume) a[baseAsset].volume = volume;
    else a[baseAsset] = {baseAsset, lastPriceUSD, volume};
    
    return a;
}, Object.create(null)));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №4

Try utilizing the reduce function along with Object.values:

let tickerA = [{pair: 'AUDUSD',baseAsset: 'AUD',lastPriceUSD: 0.74,volume: 1000}, {pair: 'AUDUSD',baseAsset: 'AUD',lastPriceUSD: 0.76,volume: 2000}, {pair: 'USDEUR',baseAsset: 'USD',lastPriceUSD: 1.25,volume: 1200}, {pair: 'USDEUR',baseAsset: 'USD',lastPriceUSD: 1.19,volume: 1500}];
const res = Object.values(tickerA.reduce((acc, { baseAsset, lastPriceUSD, volume }) => {
  acc[baseAsset] = (!acc[baseAsset] || acc[baseAsset].volume < volume) ? { baseAsset, lastPriceUSD, volume } : acc[baseAsset];
  return acc;
}, {}));
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: auto; }

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

Utilizing a variety of textures across various surfaces of a single geometry

I'm new to working with Three.js and I have a question about displaying multiple images over a plane geometry. Here is the scenario: Imagine a simplified case where we have a plane divided into tiles like this: +---+---+---+ | 1 | 2 | 3 | +---+- ...

AngularJS is unable to locate the $locationProvider module

I'm encountering an error message every time I attempt to utilize $locationProvider. Is there a specific way I should be importing the module? Error: $injector:unpr Unknown Provider Unknown provider: $locationProviderProvider <- $locationProvider ...

Patience is key when awaiting the completion of several promises

I am currently utilizing the SQLStorage feature provided by the Ionic platform. The remove function within this tool returns a promise. Within my code, I have a need to remove multiple values and then execute some additional code once all removals are comp ...

Display or conceal various objects using a single button in HTML

I've been working on creating a chatbot widget for my website, but I've run into an issue. The "Chat with us" button only shows the bot and not the close button as well. Here's what I've attempted: <input id="chat" type="button" on ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

I possess information stored within the array object below, and I aim to transform it into a different array object format

Here is the response I received from my API: let data = [ { date: '2021-04-27', formatted_date: 'Apr 27', location: [ { date: '2021-04-27', formatted_date: 'Apr 27', countr ...

Leverage the retrieved configuration within the forRoot function

Currently working on an Angular app that uses @ngx-translate. In my implementation, I am using TranslateModule.forRoot(...) to set up a TranslateLoader: @NgModule({ imports: [ TranslateModule.forRoot({ loader: { provide: TranslateLoade ...

Slideshow feature stops working after one cycle

Hey there! I'm currently working on a function that allows for sliding through a series of images contained within a div. The goal is to cycle back to the beginning when reaching the end, and vice versa when going in the opposite direction. While my c ...

Implement Vue JS to set default value(s) in an array

While browsing through Stack Overflow, I've noticed many questions related to Vue JS and selecting a default single value from an Array. My situation is a bit different - I need to compare each item's array groups with an array containing ALL THE ...

Generate a Selectpicker dynamically when a button is clicked

Wanting to insert a new row in an HTML table dynamically by clicking on an add button. The new row includes a select element with the selectpicker class. Interestingly, when I remove the selectpicker class in my script to append a new row, the select eleme ...

Does anyone know of a tool that allows you to save HTML as a standalone page?

Looking for a solution to easily send standalone .html files with no external dependencies to clients on a regular basis. The original pages are built using node.js and express, and feature libraries like High Charts. Up until now, I have been manually pre ...

Programmatically setting properties for elements

I have a question about how to programmatically add a prop to a component in my React project. Here is the scenario: In the render() method, I have the following code snippet: <TextField name="password" va ...

Load jQuery results when scrolling to the top of the window

I have a function that triggers when I click a button to fetch more data from my table. I'm attempting to make it work when the button reaches a certain distance from the top of the window, but I've been unable to achieve this so far... $(funct ...

Are there any user interface frameworks available that can replicate the aesthetic of a Mac application?

I've been searching high and low but I haven't come across any answers yet. It caught my attention that the wunderlist mac app was developed using HTML/CSS/JS, but I'm curious if they incorporated a pre-existing UI JavaScript framework into ...

Troubleshooting Jasmine Unit Testing issues with the ng-select library

Recently, I integrated the ng-select component from Github into my Angular application without encountering any console errors during runtime. It functions as expected; however, issues arise when running unit tests with Jasmine. To incorporate NgSelectMod ...

What is the best way to call a JavaScript function with multiple arguments from a Silverlight project?

I encountered an issue when trying to invoke a JavaScript function with multiple arguments from an HTML page. Here is what I am attempting to do: wbNavigator.Navigate(new Uri("http://localhost:56433/route.html", UriKind.Absolute)); object results = wbNavi ...

Can someone help clear up this confusion with CSS?

Why is image 6.png selected, when all the images are direct descendants of the div shape? Thank you for your assistance, it's greatly appreciated. As far as I know, it should select all the divs because they are all direct descendants of the div #shap ...

Automatic suggestions for my personalized npm module (written in ES6/Babel) in Webstorm

When I utilize the material-ui package in Webstorm, I am able to experience helpful auto-completion using the ctrl+space shortcut: https://i.stack.imgur.com/Pivuw.png I speculated that this feature may be attributed to the inclusion of an index.es.js fil ...

Having trouble retrieving information from combineLatest in Angular?

I'm having some trouble with fetching files to include in the post logs. It seems that the data is not being passed down the chain correctly when I attempt to use the pipe function after combining the latest data. This code snippet is part of a data r ...

Tips for updating text in a freshly opened window using JQuery or JavaScript

I have a function that is triggered by a button click to open a new window or tab, display an alert, and update text. Here is the code snippet: function nWin(p) { var setStyle = "<style rel='stylesheet'>\ .vTop {\ ...