Finding repeating elements in an array of objects

Is there a way to identify duplicates in an array based on type, name, and size, increment the amount, and then remove the duplicate entries?

[
    {
        "name": "Pizza with pepper",
        "imageUrl": "...",
        "type": 0,
        "size": 26,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Pizza with pepper",
        "imageUrl": "...",
        "type": 1,
        "size": 40,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Peperoni",
        "imageUrl": "...",
        "type": 0,
        "size": 30,
        "price": "803",
        "amount": 1
    },
    {
        "name": "Peperoni",
        "imageUrl": "...",
        "type": 0,
        "size": 30,
        "price": "803",
        "amount": 1
    }
]

Answer №1

const menuItems = [
    {
        "name": "Margherita Pizza",
        "imageUrl": "...",
        "type": 0,
        "size": 14,
        "price": "10",
        "quantity": 1
    },
    {
        "name": "Pepperoni Pizza",
        "imageUrl": "...",
        "type": 1,
        "size": 16,
        "price": "12",
        "quantity": 2
    },
    {
        "name": "Vegetarian Pasta",
        "imageUrl": "...",
        "type": 0,
        "size": 20,
        "price": "15",
        "quantity": 1
    },
    {
        "name": "Garlic Bread",
        "imageUrl": "...",
        "type": 0,
        "size": 8,
        "price": "5",
        "quantity": 3
    }
];

const mergedMenu = menuItems.reduce((total, menuItem) => {
  const key = `${menuItem.name}-${menuItem.type}-${menuItem.size}`;
  if (total[key]) {
     total[key].quantity += menuItem.quantity;
  } else {
     total[key] = menuItem;
  }
  return total;
}, {});

const finalizedMenu = Object.values(mergedMenu);
console.log(finalizedMenu);

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

The form submission button fails to function when the onsubmit function returns false

When submitting, I check two fields. If one of the two fields is checked, then I return true; otherwise, I return false. The issue I'm facing is that even when I check one of the checkboxes, the submit button does not seem to work (I use console.log() ...

Another method to verify an input using HTML5 regex and JavaScript

When working with vanilla JavaScript to check an HTML input against a regex pattern, things can get tricky. I find myself going back to the parent element to validate the input, and while it works, it's not as elegant as I would like it to be. Here i ...

JavaScript HTTP Requests

I came across this AJAX example in Stoyan Stefanov's book Object Oriented JavaScript on page 275. The example involves requesting three different files. I have a few questions that I was hoping someone could help me with! What does the line xhr.se ...

Enabling ng-disabled within an ng-repeat loop

I'm facing an issue with a form that is nested inside an ng-repeat directive. The form should only be enabled if a specific field (in this case a select dropdown) is selected, but for some reason, it's not working as expected. Can anyone provide ...

The Material-ui bug: multiple instances of the modal opening when a button is clicked

I have the following code in my render() method: render() { const classes = this.useStyles(); return ( <Paper style={classes.root}> <Table style={classes.table}> <TableBody> {this.state.deadTopics ...

Exploring the concept of data sharing in the latest version of Next.JS - Server

When using App Router in Next.JS 13 Server Components, the challenge arises of not being able to use context. What would be the most effective method for sharing data between various server components? I have a main layout.tsx along with several nested la ...

Convert the PHP datetime and timezone function to a JavaScript function

I have a helpful function in my solution that I'd like to share: public static function formatTime($time, $timezone) { $timezone = new \DateTimeZone($timezone); $time = $time->setTimezone($timezone); return \Locale::getDefaul ...

Scroll the content of a div to the bottom using JavaScript

I'm facing a situation with my code: function scrollme(){ dh=document.body.scrollHeight ch=document.body.clientHeight if(dh>ch){ moveme=dh-ch window.scrollTo(0,moveme) } } However, I am looking for a way to make it scroll only within a specific d ...

Receiving CORS response from the server for just one of the two API calls

Description of the issue: I am facing a peculiar problem where I am encountering different responses while making two calls to the same API. One call is successful, but the other returns a 504 error. Access to XMLHttpRequest at '' from orig ...

Issue with h2 tag within JQuery's read more feature

How can I modify my jQuery code to wrap the middle text in an h2 tag? I am currently using a code snippet from code-tricks. You can find the original code snippets here: $(document).ready(function() { var showChar = 100; var ellipsestext = "..."; ...

Why am I not receiving the expected feedback after submitting a request for a specific parameter in a Node.js and Express Router REST API?

Developed a Node module utilizing the Express router to facilitate the routes for the dishes REST API. Index.js file: const express = require('express'); const http = require('http'); const morgan = require('morgan'); const b ...

Guide for ordering a query by the most recent updatedAt within a nested one to many relationship

I'm dealing with a set of interconnected entities structured as follows: Entity1 -> Entity2 -> Entity3 (illustrating one-to-many relationships with arrows) I am utilizing MikroORM for this purpose. Is there a way to construct a findAndCount q ...

Creating a dynamic drag-and-drop layout in React using react-grid-layout

Utilizing the react-grid-layout package for implementing drag-drop and resize components, I have successfully achieved the functionality outlined in the documentation. Description of My Issue My challenge lies in creating a dynamic UI where the layout is ...

Show the JSON data retrieved from an AJAX request in an HTML table

After receiving the JSON response below from an AJAX call: {"items":[{"name":"MP 201SPF_1C","productNo":"123","commerceItemQty":1,"price":"$350.00","leaseOrNot":"false"},{"name":"MP 201SPF_1C","productNo":"456","commerceItemQty":4,"price":"$1,400.00","lea ...

Filtering data from an Ajax request in Angular using a filter function with JSON

Hi everyone, I recently started learning AngularJS and created a basic item list with search functionality and pagination. Everything was working smoothly, so I decided to move my list outside the controller and store it as a JSON file. Here's what ...

How does the performance contrast between "skip if condition" and "immediately return"?

Do you know if there is a performance variance between these two functions? function x() { var x = false; if(x == true) { ... Numerous lines, like 1 million ... } } function y() { var x = false; if (x != true) { retu ...

An error occurred in Python when attempting to add new values to an object, resulting in a "TypeError: ... is not JSON

Currently, I am dealing with a JSON object that looks like this: { "people":[ {"firstName":"Hasan Sait", "lastName":"Arslan", "email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="99f1f8eaf8f7b7eaf8f0edb7f8ebeaf ...

What is the most effective method for invoking an inherited method (via 'props') in ReactJS?

From my understanding, there are two primary methods for calling an inherited method on ReactJS, but I am unsure which one to use or what the best practice is. class ParentCont extends React.Component { constructor(props) { super(props); t ...

Can someone explain how to replicate the jQuery .css function using native JavaScript?

When referencing an external CSS file, the code may look something like this: #externalClass { font-family: arial; } Within the HTML file, you would use it like so: <a href="#" id="externalClass">Link</a> In the JavaScript file, you can ret ...

Updating the redux state in react by passing a variable from a child component to the parent

I'm currently in the process of updating my Redux state within a component by utilizing a variable that has been passed up to the component from a child, specifically through a form submission callback. The form is responsible for submitting a user&ap ...