Eliminate any repetitive items from the array while simultaneously boosting their quantity

Here is a list that I have:

const myList = [
  { name: 'AA', quantity: 1 },
  { name: 'AA', quantity: 1 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 1 },
  { name: 'CC', quantity: 2 },
]

I want the output to be like this:

const updatedList = [
  { name: 'AA', quantity: 2 },
  { name: 'BB', quantity: 1 },
  { name: 'CC', quantity: 3 },
]

I am trying to remove duplicates and increase the quantity when a duplicate is found, but struggling with the logic.

const uniqueSet = new Set()
const finalResult = myList.reduce((acc, item) => {
  if (!uniqueSet.has(item.name)) {
    uniqueSet.add(item.name)
    acc.push({ name: item.name, quantity: item.quantity })
  }

  // for (const iterator of myList) {
  //   if (uniqueSet.has(item.name)) {
  //     console.log('🚀 ~ file: Untitled-1 ~ line 15 ~ iterator', iterator)
  //   }
  // }

  console.log()
  return acc
}, [])

Answer â„–1

To achieve this, you can utilize the reduce method and then search for the element in the resulting array. If it does not exist, use push to add it to the array. If it does exist, simply add the current element's quantity to the existing element with the same name in the result array.

Here is the code snippet:

const list=[{name:"AA",quantity:1},{name:"AA",quantity:1},{name:"BB",quantity:1},{name:"CC",quantity:1},{name:"CC",quantity:2}];

const res = list.reduce((acc, e) => {
  const found = acc.find(x => e.name === x.name)
  found ? found.quantity += e.quantity : acc.push(e)
  return acc
}, [])

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

Answer â„–2

Using a unique method to manipulate objects and return an array with Object.values()

const items = [
  { item: 'AA', count: 1 },
  { item: 'AA', count: 1 },
  { item: 'BB', count: 1 },
  { item: 'CC', count: 1 },
  { item: 'CC', count: 2 },
]

const groupedItems = {};

items.forEach(element => {    
   const obj =  groupedItems[element.item] = groupedItems[element.item] || {...element, count: 0}
   obj.count += element.count
})

const result = Object.values(groupedItems)
console.log(result)

Answer â„–3

To efficiently combine and sum up values based on a specific property, you can use a loop like the following:

let mergedList = [];
list.forEach((item) => {
   let existingItem = mergedList.find(i => i.name == item.name);
   if (existingItem) {
       existingItem.quantity += item.quantity;
   } else {
       mergedList.push(item);
   }
});

Answer â„–4

The best approach to this problem is utilizing an object structure, as it allows for the creation of a unique entity with distinct keys.

const itemList = [
  { itemName: 'AA', itemQuantity: 1 },
  { itemName: 'AA', itemQuantity: 1 },
  { itemName: 'BB', itemQuantity: 1 },
  { itemName: 'CC', itemQuantity: 1 },
  { itemName: 'CC', itemQuantity: 2 },
];

const updatedList = itemList.reduce((accumulator, currentItem) => {
  if (!accumulator[currentItem.itemName]) accumulator[currentItem.itemName] = 0;
  accumulator[currentItem.itemName] += currentItem.itemQuantity;
  return accumulator;
}, {});

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

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

Initializing the $(this) variable prior to the function declaration

I am faced with the task of performing multiple checks based on the IDs of certain elements, all of which vary slightly. So, I created several functions to handle this, and rather than repeatedly using $(this).children ..., I wanted to create a short vari ...

How to Extract YouTube Audio URL on an iPhone

I have been working on a JavaScript code that can fetch the direct download URL for videos from the mobile YouTube website. [webView stringByEvaluatingJavaScriptFromString:@"function getURL() {var player = document.getElementById('player'); var ...

Adding up values of objects in a different array using Vue.js

Recently, I started using VueJs and encountered an object that contains arrays. One of the tasks I need to accomplish is to display the total sum of all amounts in one of the columns of the table. Here is my table structure: < ...

Exploring the variations in method declarations within Vue.js

Today, while working with Vue, I came across an interesting observation. When initially using Vue, there were two common ways to define a method: methods: { foo: () => { //perform some action } } and methods: { foo() { / ...

Error encountered on page load due to undefined variable thrown by the Express-validator validation process

In the process of constructing a contact form and incorporating express-validator for validation, I am currently focused on error handling. Below is a snippet of the code from my app.js file that pertains to this matter: // CREATE (POST) ROUTE - add new p ...

Create a Vue component that integrates with "unpkg"

I am trying to publish my component on unpkg.com. While it is currently available there, it seems to not be working as expected. I have attempted to use the same UMD build for unpkg as I do for my npm build, but it appears that a specific build may be need ...

What is causing the 'this' variable to be different from the anticipated value?

I'm encountering a problem with this code snippet. The 'this' variable is expected to hold 'Object Chart' on the lines where 'console.log' is used, but instead, it contains 'path.line'. As a result, the referenc ...

Customizing Webpack 4's Entry Point

Below is the layout of my project: -node_modules -src -client -js -styles -views -index.js -webpack.config.js -server -.babelrc -package -package-lock -README.md -webpack ...

The speed of the jQuery mouse scroll script remains constant and cannot be altered

I've been searching online... I attempted to adjust the scrolling settings on my website but nothing seems to be working. Does anyone have a guide or list of mouse scroll jQuery scripts and functions? (I've cleared caches, performed cross-brow ...

Retrieve the value of a CSS class property regardless of whether it is actively being utilized

I am facing a dilemma where I need to determine the value of the 'width' property for a css class named 'foo' (example: ".foo { width:200px}" ). However, there may not be an element with this class in the dom yet. My goal is to retrie ...

Ensuring the correctness of phone numbers by validating them with country codes through the use of

I'm currently working on validating phone numbers using intl-tel-input, following the example provided at Below is the code snippet I've been using: var telInput = $("#phone"), errorMsg = $("#error-msg"), validMsg = $("#valid-msg"); // initial ...

Dealing with Uncaught Type Errors in the Fixed Data Table

I am attempting to implement a fixed data table using the following code snippet. var MyCompi = React.createClass({ getInitialState: function() { return { rows : [ {"id":1,"first_name":"William","last_name":"Elliott","email":"<a ...

Problem with integration of Bootstrap datetime picker in AngularJS directives

I am currently utilizing the Bootstrap Datetime picker to display data from a JSON file in calendar format. The data is first converted into the correct date format before being shown on the calendar, with both a To date and From date available. scope.onH ...

Equal size images displayed within cards in Material UI

Is there a way to create a list of Material UI components with images that have uniform height, even if the original images vary in size? I want to make all image heights responsive and consistent across all cards. Any suggestions on how to achieve this? ...

Instructions for creating a distinct click listener for each <img> element inside a table cell

Within my table, each row contains multiple columns with images as data. I successfully implemented a 'common listener' that is triggered when any image within a table row is clicked. $('#mytable tbody td img').click(function () { // ...

Using ng-if in AngularJS to compare two objects

I am transferring between controllers with different formations, and I am attempting to use "ng if" to compare the ids, but it is not functioning as expected. Below is the code snippet: var postsApi = 'http://mywebsite.com/wp-json/posts?filter[p ...

Methods for transferring data from child to parent in TSX components

There is a value in the parent component value={this.onUpdate(index)} and the onUpdate function manipulates the value and index In the child component, there is an input field with onChange={this.handleText(index)} This calls a method that tries to p ...

Update the content of a bootstrap modal dialog following a successful upload

As part of a new service, I am modifying data in a database using a bootstrap modal dialog. However, I'm facing an issue where the name of a recently uploaded file is not appearing in the modal dialog body until I close and reopen it. Is there a way t ...

Utilizing database information for interactive objects in Three.js: A step-by-step guide

I need to display specific text data for each object based on database entries in my project. However, despite creating a cube for each entry in the database, I'm encountering issues with undefined data. It seems like my code should work, but it' ...