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

What other methods are available to verify null and assign a value?

Is there a more efficient approach for accomplishing this task? theTitle = responsesToUse[i]["Title"]; if(theTitle == null) theTitle = ""; ...

Dynamically loading an iFrame source and automatically populating input forms using Javascript explained

My current challenge involves retrieving URL parameters successfully and using them to decide which iframe src to populate. Additionally, I need to autofill the form created via the form src with other parameters. However, I am faced with two main issues. ...

Troubleshooting CSS compatibility issues in Firefox browser (or HTML rendering as plain text)

In a unique web page comparing two photos, the clicked one changes, but there's an issue in Firefox where HTML displays as text and links don't work. CODE:- * { box-sizing: border-box; } html { height: 100%; } body { height: 100%; mar ...

Angular JS Tab Application: A Unique Way to Organize

I am in the process of developing an AngularJS application that includes tabs and dynamic content corresponding to each tab. My goal is to retrieve the content from a JSON file structured as follows: [ { "title": "Hello", "text": "Hi, my name is ...

Validation script needed for data list selection

<form action="order.php" method="post" name="myForm" id="dropdown" onsubmit="return(validate());"> <input list="From" name="From" autocomplete="off" type="text" placeholder="Starting Point"> <datalist id="From"> <option ...

MXGraph has an issue where edges fail to be redrawn after being moved

Perhaps this question may seem trivial, but I am facing an issue in my code and seeking guidance from the community. I am working on a javascript mxGraph application within Angular7. Specifically, I have modified the ports.html example for my project. Wh ...

Mastering Data Transfer in jQuery: A Guide to Migrating Event Information from .on(dragstart) to

I need help with transferring information between an .on(dragstart) event and an .on(drop) event. However, when I run the code below in Chrome, I encounter an error message: 'Uncaught TypeError: Cannot read property 'test' of undefined' ...

Retrieve information from a .json file using the fetch API

I have created an external JSON and I am trying to retrieve data from it. The GET request on the JSON is functioning correctly, as I have tested it using Postman. Here is my code: import "./Feedback.css"; import { useState, useEffect } from " ...

Electron Developer: "An issue has occurred within the primary process - Callback function missing"

My Electron application runs smoothly when launched from the command line with npm start. However, I am now looking to distribute the application as user-friendly installers for Mac/Windows/Linux. To achieve this, I am utilizing Electron-Builder for packag ...

Instead of relying on traditional AJAX for receiving remote commands, consider using a new Image object in your code like this: `var

How efficient is the following method: var i = new Image(); i.src = 'http://secondary.domain.com/command.gif?command=somecmd&rand=' + ...epoch time....; ... utilizing mod_rewrite to redirect the above URL to a PHP script ... Is this an effe ...

Transform the output of a MySQL query into a specific JSON format using PHP

My table contains data stored in the following JSON format: https://i.stack.imgur.com/Ab5ug.png The JSON result obtained from a query is as follows: [{ "cnt": "1", "category_name": "Entertainment", "event_name": "Typhoon Sample", "year_o ...

injecting javascript dynamically using jquery

I am attempting to conditionally load a script in the case that the browser being used is IE8. To achieve this, I have employed jQuery's .getScript function as it allows me to execute certain actions after the script has been loaded. The issue lies in ...

Creating a Commentary System in VueJS Similar to Medium

One feature that I admire in Medium is their commenting interface, which allows users to highlight specific portions of an article and leave comments. I am interested in integrating a similar commenting feature into a VueJS application. While researching ...

The hunt is on for greater value within the index

My requirement is to check the text content of a box. If it matches any value stored in an ARRAY, then I have to execute a specific action. var ARRAY1 = ["Saab", "Volvo", "BMW"]; if (select[i].innerHTML.indexOf('ARRAY1') != -1){//code here} ...

How can I extract the JSON value as a string?

I have a scenario where I define two objects. The first object, BOB, has properties "name" with a value of "bob" and "height" with a value of 185. var BOB = { "name": "bob", "height": 185 }; The second object, PROPS, references the height property from ...

jQuery sends ajax success to input type number

I am encountering an issue with the ajax success loading function when using input type number. Interestingly, when I switch the input type to text, it works perfectly fine. However, once I change the input type back to number, the loading ceases. <s ...

PHP encountering a bad escaped character while parsing JSON using JSON.parse

I'm encountering an issue with JSON parsing. In my PHP code, I have the following: json_encode(getTeams(),JSON_HEX_APOS); This returns a large amount of data. Sample data: To provide more clarity, let's assume I have this: my_encoded_data ...

Which is better for handling events - jQuery delegation or function method?

Which approach is quicker and has broader browser support? 1. Utilizing a JavaScript function such as: function updateText(newtext) { $('div#id').text(newtext); } and incorporating it into an element's onclick event: <button onc ...

Leverage the power of Angular's $http module in conjunction with Django's urlpatterns to fetch

I am attempting to send a $http GET request to a Django URL pattern in order to retrieve a .json file. Is it possible to use urlpatterns to return a file instead of a view? Is this scenario achievable, or are there limitations preventing this from working ...

Upon running `npm start`, an unexpected token error arises in the file originating from a local

After developing my first-app with the help of create-react-app, I incorporated some components from Material-UI. Everything was running smoothly when I launched it using npm start. Upon completion, I decided to extract the nice-component into its own fol ...