Utilize JavaScript to add the price of a duplicate item to the first distinct object in an array

Product List

[{ id: 1, title: 'shirt', price: 2000 }, 
{ id: 2, title: 'shirt', price: 4000}, 
{ id: 3,  title: 'tshirt', price: 10000}]

Desired Result

[{ id: 1, title: 'shirt', price: 6000 },          // 2000 + 4000
{ id: 3,  title: 'tshirt', price: 10000}]

Attempted Various Methods with no Success.

I have been able to retrieve distinct products but require the sum of prices as well.

let result = products.filter((product, index, self) =>
  index === self.findIndex((t) => (t.title === product.title))
)
console.log(result);

Answer №1

If you have a hash table containing objects with the same title, you can extract the values from the hash table.

const
    data = [{ id: 1, title: 'shirt', price: 2000 }, { id: 2, title: 'shirt', price: 4000}, { id: 3,  title: 'tshirt', price: 10000}],
    result = Object.values(data.reduce((r, o) => {
        if (r[o.title]) r[o.title].price += o.price;
        else r[o.title] = { ...o };
        return r;
    }, {}));

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

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

Making synchronous HTTPS requests in Node.js is a useful feature for

Here is the code snippet I am working on: `//... .then(function () { var opts = { method: 'GET', agent: new https.Agent({ rejectUnauthorized: false }) }; var url = 'https://***'; ret ...

Combining arrays using parent loop in PHP

I am working with a dataset that includes information about patients, rooms, and payment methods. These datasets are represented as arrays of objects structured like this: $rooms = [ (object) [ 'roomCode' => 1, 'roomName&ap ...

"Exploring the issue of object property not updating within a React Hook that utilizes an array of objects

My question is how to properly update a property of an object inside an array using useState in React. I am having trouble updating the quantity property, can someone please help me identify the error? ( The initial state is set up initially, and the rest ...

What is the best way to arrange a 2-dimensional integer array in C#?

I recently started learning C# and came across an exercise that challenged me to sort numbers in an array from smallest to largest without utilizing another array or converting it to a 1D array. This is the approach I took, but unfortunately, it's not ...

Modify AngularJS behavior to show or hide elements when the user hovers over them

In my template, I display a series of "icons". <div ng-repeat="data in items | orderBy:'-timestamp'"> <div class="icon"> <i>1</i> <span>2</span> </div> </div> To hide i and ...

JavaScript Deviance

I am facing an issue with my JS code while trying to send form data to a .php file via AJAX. The problem occurs when the input fields are filled - for some reason, my client-side page refreshes and the php file does not get executed. However, everything wo ...

Creating a Powerful Application with Typescript and NodeJS

Currently, I am attempting to utilize Got with Typescript and ESM. With Got being written in Typescript itself, I anticipated a seamless integration. Alas, even after diligently following this comprehensive guide authored by the creator of Got, I am unable ...

Displaying JSON with AngularJS HTTP Get request won't work in my project

As I delve into the world of AngularJS, I find myself caught up in a puzzle that has consumed my entire evening. My goal is to fetch JSON data from a random generator and display it in the view using a service. While {{ main.title }} seems to be working ju ...

Exploring the animation potential of HTML5 canvas and Javascript through utilizing putImageData with animated gifs

I am interested in modifying the image data of each frame in an animated gif while it is playing in a web browser, using HTML5 canvas and Javascript. For instance, I would like to convert every frame to grayscale dynamically as the gif plays. Is this achie ...

Apply the "ng-class" directive only if there is an <a> element located after the specified element

My issue involves a list of items categorized by labels, with a search filter applied. The problem arises when the labels appear in the search results even though the lists themselves are empty. I need to hide the relevant label if there are no items prese ...

What is the best way to conditionally render one of several components in a manner that is compatible with React's change detector?

Within my CRUD application, I have incorporated various reusable components such as a "generic" DialogComponent, along with several non-reusable components. Throughout the development process, I have encountered numerous instances where I need to either: ...

Error: Trying to play the Snake Game with the P5.js Library, but getting the message "(X)

During my journey of coding a snake game by following a tutorial, I encountered an issue that the instructor had not faced before. Strangely enough, I am unable to identify the root cause of this problem. To aid in troubleshooting, I meticulously commente ...

Enhance a path SVG component with properties for a map in a React application

My goal is to develop a strategy game using an SVG map that I have created. I want to include attributes such as "troops" in each "path" representing territories, along with other properties. Can I add these attributes to individual paths and then use this ...

Keep the Bootstrap dropdown menu open when the search bar is in focus

I am working on a customized bootstrap dropdown menu that needs to remain open when the search bar within the Events dropdown is focused. I have managed to make it open and close on hover, but now I need it to stay open under certain conditions. Below is ...

What is the best way to eliminate opacity in an element using react dnd?

When I use react-dnd to drag an item, the element being dragged becomes almost completely opaque. I would like to increase its visibility, is there a way to achieve this? In the image below, the upper element is the one being dragged and the bottom one is ...

developing components in Vue by extracting common logic from data functions

Within my application, there exists a menu page component. This particular component boasts multiple static data and initialized variables. As illustrated below: data() { return { tableInfo: { headers: ..., contents: ..., pagination ...

Tips for obtaining a phone number through the Google API

This is the code I have been working on: function displayLocationInfo(placeLatLong, placeNames) { var placeNames = placeNames; var planLat = placeLatLong; var newStr = planLat.replace(/[(\)]/g,''); var aCars = newStr.split(&apos ...

A-Frame Visual Illumination

In my A-Frame AR scene, there is an image (transparent png) that can be moved and resized using gestures. My goal now is to adjust the brightness of this image based on the light estimated from the camera input. I have successfully implemented the light e ...

"Learn the steps to access a JSON file directly from a URL within a Next.js

My goal is to upload a JSON file to the server from a URL, open it, parse it, and display its features on Google Maps. However, I am encountering an error with the "fs" library preventing me from opening the file. Below is the code: "use client" ...

Adjust the HTML 5 range slider to update according to the selected value

Is it possible to create a custom marker on an HTML5 range input element? I'm looking for a way to change the design of the circle marker as it moves along the scale from 1 to 10. Specifically, I want to change the color of the marker based on its po ...