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

CSS file not loading in an ExpressJS application

I'm facing an issue with my ExpressJS web app where only the HTML files are loading but the CSS rules are not being applied. I have linked the HTML file with the CSS file and also included express.static(path.join(__dirname, 'css')) in my ap ...

Issues with the directory for Chrome

Currently, I am utilizing jQuery and running an HTML file on my local machine without a server. Interestingly, the code works perfectly fine on Firefox but encounters issues on Chrome: $('#result').load('test.html'); It appears that t ...

Tips for addressing the Stale Element Reference Exception when locating an element in JMeter

Trying to locate an element with a structure similar to the following: <div> <div> <div> <ul> <object id = "obj" #document (link here) <html> <head> </head> ...

Using VueJS to apply filters to an object causes a decrease in my application's performance

Recently, I've been working on implementing a filter for a search bar. However, I've noticed that whenever I input something into the search bar, there is a noticeable delay as it loads the entries. I'm not sure if this issue is related to ...

The true essence of Angular values only comes to light once the view has been updated

Here is the HTML code I am working with : <div class="container-fluid"> <div class="jumbotron" id="welcomehead"> <br><br><br><br><br><br><br><br><br><br> ...

Unable to update the numerical value in the Material-UI version 5 TextField component

When attempting to display the decimal value 1.0 in the MUI5's TextField component, I encountered an issue. While I can change its value using the icons within the TextField, inputting any value directly seems to be ineffective. Additionally, backspac ...

Splitting files with Webpack generates dynamic chunk files

Anticipating to only have two distinct chunks named vendors and commons, webpack unexpectedly generates a new chunk file for specific entries with a delimiter. optimization: { splitChunks: { chunks: 'all', cacheGroups: { ...

jQuery custom slider with advanced previous and next navigation capability for jumping multiple steps

I am currently learning jQuery and programming in general. Instead of using a pre-built plug-in, I decided to create my own image slider/cycle from scratch to keep the code concise and improve my skills. My function goes through each li item, adding a &ap ...

How to set a background image in Android using an array path for the image location

I have an array like this: final String[][] dataArr = { {"R.drawable.bengaltiger", "bengaltiger"}, {"R.drawable.cat", "cat"}, {"R.drawable.chimp", "chimp"}, {"R.drawable.eagle", "eagle"}, {"R.drawable.frog", "frog"} ...

Restarting an Angular app is necessary once its HTML has been updated

I've encountered an interesting challenge with an application that combines MVC and Angular2 in a not-so-great way. Basically, on the Index page, there's a partial view loading the Angular app while also including all the necessary JavaScript li ...

Tips for managing CSS/style conflicts in JavaScript/AngularJS applications

I am new to AngularJS and I have a requirement to assign CSS properties to a component at the JavaScript file level. When I debug my code after applying the CSS styles to the component, I can see that all the applied CSS properties are behaving as expected ...

What is the best way to find the most similar arrays in two lists using Python?

My task involves detecting objects on images sized at 2400x3000 pixels. While the sizes of the objects remain consistent across all images, each image may be slightly different due to factors like rotation or skewing. To ensure accuracy, I aim to use the b ...

JSON is often portrayed as a singular value

I am attempting to save settings in my SQL Database and then restore them using ajax and php. However, I am encountering an issue where only one long JSON Value is returned instead of three separate values for each setting. Settings: {"setting1":"true","se ...

Utilize text wrapping to ensure a fixed maximum height for content display

I am in need of a div that contains text spanning multiple lines, with both a fixed width and a maximum height. Currently, I have applied the CSS property overflow: hidden;. However, my issue arises when the last line of text exceeds the maximum height of ...

Struggling with sending form data to the back end when uploading images in Angular

I've been facing a challenge trying to implement profile picture upload alongside standard text data and sending it all to the backend to create a new user through mongoose. Despite my efforts, using tools like ng-file-upload/angular-file-upload and e ...

Utilizing variables in Angular service to make API calls

Currently, I am working on accessing the Google Books API. Initially, I was able to directly access it in my controller but now I want to follow best practices by moving the business logic into a directive. HTML <form ng-submit="search(data)"> < ...

Creating a customized plugin in JavaScript that utilizes a local JSON/GeoJSON file

I am relatively new to Drupal and currently working on developing a custom map module. While my module functions correctly and displays the map along with relevant information, I encountered a challenge regarding calling my geojson file using a hard-coded ...

Begin by executing the initial commit task with Git through Gulp, followed by performing the

I am currently working on a project and I am trying to use gulp to commit and push to git. However, I am encountering an issue where the push task is not waiting for the commit task to complete before running... Can anyone assist me with this? I want to s ...

Unable to input information into Textbox in real-time

Having trouble entering data from one page to another using ng-model. After filling in some information in a textbox and moving to the next page, I want the same data to be entered when I return to the previous page. I've written the code but it doesn ...

sending a pair of variables via jQuery and AJAX

Having difficulty posting two variables using ajax and jquery when a button on a confirm window is pressed. Each variable can be displayed separately, but not both at the same time. UPDATE - Issue resolved. I overlooked including a necessary file. My mist ...