In JavaScript using Vue.js, you can compare various objects within an array and calculate the total sum of their values based on a shared

This task may pose a challenge for those new to programming, but seasoned developers should find it relatively simple. I've been searching for a solution without success so far, hence turning to this platform for help.

Here's the scenario at hand: we have an array of objects, as illustrated here:

const array = [
  {Id: 0, Name: 'John', Currency: 'USD', Amount: 25},
  {Id: 1, Name: 'Matt', Currency: 'EUR', Amount: 460},
  {Id: 2, Name: 'Lisa', Currency: 'YEN', Amount: 60000},
  {Id: 3, Name: 'Pete', Currency: 'EUR', Amount: 2400}
]

The objective is to merge similar currencies and their corresponding values, resulting in a consolidated representation:

(e.g. Currency: 'EUR' (obj1 & obj2), Amount: 460 (obj1) + 2400 (obj2) = 2860)

Therefore, the desired outcome should resemble the following:

const finalarray = [
  {Currency: 'USD', Amount: 25},
  {Currency: 'EUR', Amount: 2860},
  {Currency: 'YEN', Amount: 60000}
]

In the final result, other keys from the original objects can be omitted if necessary. The primary focus is on comparing and merging values based on a shared key among objects.

I am utilizing Vue.js within my project, requiring the use of JavaScript for solving this issue. While simplicity is preferred to keep the code concise, the paramount requirement is functionality. I have a Computed property named currencyList() that will produce the updated array.

Your assistance is greatly appreciated!

Answer №1

After some quick thinking, I came up with a solution:

const sumByCurrency = (array) => array.reduce((result, item) =>
              result.set(item.Currency, (result.get(item.Currency)||0) + item.Amount), new Map());

const summarizedValues = Array.from(sumByCurrency(array), item => ({item[0]: item[1]}))

This solution has a time complexity of O(n), which is acceptable. It can also be further optimized for readability.

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

"Looking to disable the browser shortcut for ctrl-N and instead trigger a function when this key combination is pressed? Check out the JS Fiddle example provided below

I recently incorporated the library shortcut.js from In my project, I attempted to execute a function when CTRL + N is pressed. The function executed as expected; however, since CTRL + N is a browser shortcut for opening a new window in Mozilla 8, it also ...

Modifying the values of Highcharts-Vue chart options does not result in any changes once they have been

I recently started incorporating Highcharts into my Vue project using the highcharts-vue library. A) Initially, in pure JavaScript, the following code snippet functions as expected: let b = 5; let data = { a: b } console.log('data', data.a) ...

Attempting to create a C program that utilizes the bubble sort method to alphabetically sort a set of 25 words from a 2D

I am able to successfully read in the strings, but I am struggling with implementing bubble sort to arrange them alphabetically. However, when I run the code, I keep encountering the error message "Segmentation fault (core dumped)". Here is my current im ...

Different method for adding child elements to the DOM

When creating a DOM element, I am following this process: var imgEle = document.createElement('img');     imgEle.src = imgURL;             x.appendChild(imgEle); Instead of appending the last line which creates multiple img elements ev ...

What is the best way to delay Angular for 5 seconds before initiating a page transition?

Just a quick inquiry - is there a way to have Angular wait for 5 seconds before redirecting to a different page? I attempted to implement this functionality within my function, but it doesn't appear to be functioning as expected: setTimeout(() => ...

Popper.js failing to initialize during page load

After attempting to initialize Popper.js as shown below, I am encountering an issue where nothing is happening. $().ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); Interestingly, when I apply the same code to a button, it w ...

The ng-include feature seems to be malfunctioning

After building a basic web page using AngularJs, I ran into an issue when attempting to integrate header.htm into index.html - nothing was displaying in the browser. index.html <html> <script src="https://ajax.googleapis.com/ajax/libs/angul ...

Error compiling: Cannot locate module '../../common/form' within 'src/components/time'

An attempt to import the file form.jsx into the file time.jsx resulted in an error: Error message: Module not found: Can't resolve '../../common/form' in 'src/components/time' //src //common //form.jsx //compon ...

Error: Unable to access the 'CustomerId' property because it is undefined

Recently, I made some updates to my website. As part of the upgrade process, I switched to AngularJS v1.7.6 and JQuery v1.12.1. However, after making these changes, I encountered an error in my console log. TypeError: Cannot read property 'CustomerId ...

Issue encountered while compiling all handlebars templates into a single JavaScript file

Below is the structure of my folders: app └───templates ├───templ1.hbs ├───templ2.hbs └───templ3.hbs I am looking to compile (precompile) all templN.hbs handlebars template files into one templ.js file. However ...

Explore innovative ways to display mathematical equations dynamically on the browser using NextJS version 13.3.0 or consider alternative solutions for showcasing math content with

I'm currently working on developing a web application that allows users to input LaTeX expressions, which are then dynamically displayed in another div or updated within the same input field. After some experimentation with Mathquill and NextJS v13.3 ...

"Implementing a commenting directive to enhance code clarity with eslint-plugin-vue integration

After receiving an error when naming the Vue component List.vue, changing it to Lists.vue resolved the issue. https://i.stack.imgur.com/F5ziw.png Curious as to why this occurred? ...

Which is more advantageous: returning a value or returning a local variable?

While the title may not be the best descriptor in this situation, I am unsure of how to phrase it any better. Both of these functions perform the same task: function A(a, b) { return a * b; } function B(a, b) { var c = a * b; return c; ...

The functionalities of Google Maps are experiencing issues within AngularJS when utilizing the $route feature

Having Issues with Google Maps in AngularJS when using <ng-view></ng-view> Routing Configuration app.config(function($routeProvider, $locationProvider) { $locationProvider.html5Mode(true); $routeProvider .when('/', { t ...

Issues arise when attempting to retrieve information in NextJS from a local API

One of my coworkers has created a backend application using Spring Boot. Strangely, I can only access the API when both our computers are connected to the same hotspot. If I try to access the other computer's API and port through a browser or Postman, ...

"Utilize PHP to access an object's properties in a manner similar to an array

Consider the JSON object presented below: $json = '{ "Name": "Peter", "countries": { "France": { "A": "1", "B": "2" }, "Germany": { "A": "10", "B": "20" }, .... } }'; I am looking for a way to ...

When you zoom in, the HTML elements tend to shift out of place

Spent the entire day yesterday attempting to make my page responsive while Zooming In, but I just can't seem to get it right. Even after adding height and weight, elements still get mixed up when zooming in on the page. I've scoured countless w ...

JavaScript has issues with undefined array elements

Even though there is data in bindInfo, the array elements in Bind are showing as undefined. Any recommendations? let bindinfo = { clientid: 1, clientname: 'Web Client', nowutc: now_utc, bindlist: Bindings(this.props.bindDetails) ...

Confirm that the input into the text box consists of three-digit numbers separated by commas

Customers keep entering 5 digit zip codes instead of 3 digit area codes in the telephone area code textbox on my registration form. I need a jQuery or JavaScript function to validate that the entry is in ###,###,###,### format without any limit. Any sugge ...

Error message: "Root resolution error encountered". Need assistance in granting watchman access?

After setting up a react-native starter project, I was prompted to allow watchman access to my system's files. Unfortunately, I declined and now whenever I try to run the folder, I encounter the following error: Error: unable to resolve root /Users/ck ...