Tips for combining or adding duplicated values in a Javascript array

I am facing a problem with an array object that looks like this:

[
  {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, 
  {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000}
]

When I try to add the same values, it duplicates the items like this:

[
  {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000},
  {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000},
  {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000}
]

My aim is to merge duplicate values to have the result like this:

    [
  {"item_id":1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000},
  {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":2,"original_price":1350000,"total_price":2700000}
]

I need help to figure this out. Can someone please assist me?

Answer №1

Check if the item is already in the list before adding it:
if (items.indexOf(toAdd) != -1)
   items.push(toAdd)

Another option is to use jQuery grep, which will give you a list of arrays containing the specified values

Use jQuery grep to check if the item ID is not already present in the list
if  (($.grep(items, function(e){ return e.id == toAdd.id; })) == 0)
   items.push(toAdd)

Answer №2

To add the new object to the array only if it is not already present and update it otherwise:

  • You must first check if it exists by utilizing the Array#some() method.
  • If it does exist, then modify its qty and total_price using the index of the found item.
  • If it doesn't exist, simply append it to the array.

This is how your code should look like:

var found = -1;
if (arr.some(function(el, i) {
    if (el.name === obj.name)
      found = i;
    return el.name === obj.name;
  })) {
  arr[found]["qty"] = arr[found]["qty"] + obj["qty"];
  arr[found]["total_price"] = arr[found]["total_price"] + obj["total_price"];
} else {
  arr.push(obj);
}

Demo:

var arr = [{
    "item_id": 'X',
    "name": "DOTA 2 Backpack",
    "image": "XXX",
    "qty": 1,
    "original_price": 1450000,
    "total_price": 1450000
  },
  {
    "item_id": 'X',
    "name": "Mobile Legend Backpack",
    "image": "XXX",
    "qty": 1,
    "original_price": 1350000,
    "total_price": 1350000
  }
];

var obj = {
  "item_id": 'X',
  "name": "Mobile Legend Backpack",
  "image": "XXX",
  "qty": 1,
  "original_price": 1350000,
  "total_price": 1350000
};
var found = -1;
if (arr.some(function(el, i) {
    if (el.name === obj.name)
      found = i;
    return el.name === obj.name;
  })) {
  arr[found]["qty"] = arr[found]["qty"] + obj["qty"];
  arr[found]["total_price"] = arr[found]["total_price"] + obj["total_price"];
} else {
  arr.push(obj);
}

console.log(arr);

Answer №3

Take a look at this information, it may be beneficial to you.

If you're interested, check out the Array Iteration methods

var array1 = [
  {"item_id":X,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, 
  {"item_id":X,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000}
];

var array2 = [
  {"item_id":X,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000},
  {"item_id":X,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000},
  {"item_id":X,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000}
]

var props = ['name', 'item_id'];

var result = array1.filter(function(o1){

    return !array2.some(function(o2){
        return o1.item_id=== o2.item_id;         
    });
}).map(function(o){

    return props.reduce(function(newo, name){
        newo[name] = o[name];
        return newo;
    }, {});
});

Your Output:

[
  {"item_id":X,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000},
  {"item_id":X,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000}

]

I hope this is helpful for you!

Answer №4

If you're looking to perform a comparison using the element's item_id, consider utilizing the Array.prototype.reduce() method.

Check out this code example:

const array = [{"item_id": 1,"name":"DOTA 2 Backpack","image":"XXX","qty":1,"original_price":1450000,"total_price":1450000}, {"item_id":2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000}];
const newVal = {"item_id": 2,"name":"Mobile Legend Backpack","image":"XXX","qty":1,"original_price":1350000,"total_price":1350000};

const addElement = (arr, val) => {
  return arr.reduce((a, c, i) => {
    if (c['item_id'] === val['item_id']) {
      a.found = true;
      c.qty += val.qty;
    }
    
    a.result.push(c);
    
    return !a.found && i + 1 === arr.length
      ? [].concat(arr.result, val)
      : a;
  }, {result: [], found: false});
};


console.log(addElement(array, newVal).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

Dynamic web page updates from server using an Ajax request

I have a JavaScript client application and an Express.js server. I am looking to update a page on my server with information sent through an AJAX call from my client application. I need the page to be updated in real-time. Here is the code snippet in my ...

Include parameters for a pagination system

I have a script that fetches data from my database and generates pagination. Everything is working fine, but now I want to include a conditional statement to differentiate the user level as New, Current, or Renewing client. I've already set up some s ...

What steps should I take to successfully install using npm if I keep encountering the same error?

Every time I attempt to install a package using npm, I encounter the following warning: npm WARN EBADENGINE Unsupported engine { npm WARN EBADENGINE package: '<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c7b3aeaba2b3be ...

Trigger an alert message upon loading the HTML page with search text

I need to search for specific text on a webpage and receive an alert if the text is found. <script type='text/javascript'> window.onload = function() { if ((document.documentElement.textContent || document.documentElement.innerText ...

Troubleshooting Cache Problems in Express.js 4.0 during Development

Recently, I created a fresh express.js application using the express-generator. However, when I attempt to make modifications, none of them seem to reflect when I refresh the browser. I have tried various solutions found online, including: Disabling Chr ...

Is it possible to retrieve any user data by id using Vue 3 Firebase Auth?

I'm a newcomer to vue/firebase and I've been able to easily access the "current user" data from authentication. However, I am struggling to write a JavaScript composable that can retrieve the user object or at least displayName when passing in an ...

Tips for refreshing the tawk.to widget when the language changes with the help of i18next

Utilizing i18n-jquery for language switching and integrating the tawk.to chat widget, I've successfully loaded different languages on page reload. However, due to i18n not refreshing the page (which I don't want to do), I need to figure out how t ...

Split an array of simple data types in JavaScript into separate sections

Is there a way to divide an unordered array of primitive types into specific segments like this: var array = [102,103,104,201,203,204,303,301,302,405,406,408,101]; => newArray = [[101,102,103,104],[201,203,204],[303,301,302],[405,406,408]] The divisio ...

Is the callback still triggered even after the off function is called?

Can someone help me with a scenario where despite calling the off on a reference, the callbacks are still being triggered repeatedly? var ref = new Firebase('https://example.firebaseio.com/123456'); for (var n = 0; n < 1024; ++n) { ref.pus ...

Guide on hiding the sidebar in mobile view and enabling toggling on click for both mobile and other devices with the use of vue.js and bootstrap4

I need assistance with transitioning my code from pure Bootstrap4 and JavaScript to Vue.js. When I tried implementing it in mobile view, the sidebar is not showing. Below is the code snippet that I am trying to change for Vue.js, but I keep encountering an ...

Display all months on mobile screen using Mui DesktopDatePicker

Looking for a Better Date Range Picker I've been working on a project that requires a date range picker, and I opted to use the Mui date range picker. While it works well on desktop, I encountered an issue with mobile view where only one month is sho ...

Encountering npm install failure post updating node version

When attempting to execute npm i, the following error message is now appearing: npm i npm ERR! path /home/ole/.npm/_cacache/index-v5/37/b4 npm ERR! code EACCES npm ERR! errno -13 npm ERR! syscall mkdir npm ERR! Error: EACCES: permi ...

Simple server using node.js and express to host an HTML file and associated resources

I am currently experimenting with frontend development and need a basic web server to quickly start projects and serve files. Specifically, I have one index.html file along with some css/js/img files. I decided to work with Node.js and Express for this pur ...

Tips for creating visually appealing text on a web browser with the help of open-source libraries

Have you ever noticed that no matter how we display text on webpages, whether it's in a <p> tag or an <h1> tag, the result is always the same? (a screenshot of a rendering done in Firefox) Do you struggle with pixelated areas on the curv ...

Struggling to make jQuery code function in an external file without causing clashes with additional jQuery code

When incorporating this simple code into its own separate file, I encounter some jQuery conflicts with another piece of code. jQuery(function ($) { $(".tabContents").hide(); $(".tabContents:first").show(); $("#tabContainer ul li a").click(fun ...

Learn how to dynamically change a class name with JavaScript to alter the color of a navbar icon

I have little experience with javascript, but I want to make a change to my navbar icon. Currently, my navbar has a black background with a white navbar icon. As I scroll the page, the navbar background changes to white and the font color changes to black. ...

What is the response of Express when it encounters numerous identical asynchronous requests from the same origin?

Currently, I am utilizing Express.js for my project. There is an async function that performs a task that can take anywhere from 20 to 30 seconds to complete. Once the task is done, it increases a user's counter in the database. However, users are req ...

Tips for fixing the TS2345 compilation error when working with React

Attempting to implement the setState method in React has resulted in a compile error. Any solutions to this issue would be greatly appreciated. Frontend: react/typescript articleApi.tsx import axios from 'axios'; import {Article} from '../ ...

Utilizing Angular JS to Manage Controller Events

I am currently working on an application that requires saving a large amount of data in cascade, similar to a typical master-detail view. Within this view, there is a "Save All" Button which saves each row in an iteration. This process triggers jQuery cus ...

Utilize JavaScript conditions to dynamically apply styles within your web application

I am facing a challenge with managing two separate <style> tags that each contain a large number of styles and media queries. The issue is that one set of styles is intended for desktop users, while the other is meant for mobile users. When both se ...