Eliminating duplicates in an array of objects and calculating the sum of a specific key using JavaScript

In my JavaScript code, I have an object called obj. I am trying to figure out how to remove duplicates in the info array and calculate the sum of the quantities (qty) for each unique key. Can you help me with this problem?

function updateTotalQuantity(obj) {
  return obj.map(item => ({
    ...item,
    total: item.info.reduce((acc, curr) => acc + curr.qty, 0)
  }));
}

var obj = [
 {id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2},{idx:2, qty: 2}], code: "sample1", total: 1},
 {id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 2}
]

Desired Result:

[
 {id:1, info:[{idx:1, qty: 1}, {idx:2, qty: 2}], code: "sample1", total: 3},
 {id:2, info:[{idx:3, qty: 2}, {idx:4, qty: 2}], code: "sample2", total: 4}
]

Answer №1

To streamline the data and remove any duplicate entries in rows, you can utilize the reduce method along with the Map function:

var details =[
 {id:1, information:[{index:1, quantity: 1},{index:2, quantity: 2},{index:2, quantity: 2}], code: "example1", total: 1},
 {id:2, information:[{index:3, quantity: 2}, {index:4, quantity: 2}], code: "example2", total: 2}
];

var outcome = details.reduce((accumulator, item)=>{
    item.information = [...new Map(item.information.map(i=>[i.index, i])).values()];
    item.total = item.information.reduce((sum, {quantity})=>sum+quantity,0);
    accumulator = [...accumulator, item];
    return accumulator;
},[]);

console.log(outcome);

Answer №2

Give this example a shot, even though my outcome doesn't match the expected results. Give it a try

const data = [
  {
    id: 1,
    info: [
      { idx: 1, qty: 1 },
      { idx: 2, qty: 2 },
      { idx: 2, qty: 2 },
    ],
    code: "sample1",
    total: 1,
  },
  {
    id: 2,
    info: [
      { idx: 3, qty: 2 },
      { idx: 4, qty: 2 },
    ],
    code: "sample2",
    total: 2,
  },
];

let result = data.map((entry) => {
  return {
    ...entry,
    info: entry.info.reduce((prev, curr) => {
      const item = prev.find(
        (element) => element.idx === curr.idx && element.qty == curr.qty
      );

      if (!item) {
        prev = [...prev, curr];
      }

      return prev;
    }, []),
  };
});

result = result.map((entry) => {
  return {
    ...entry,
    total: entry.total + entry.info.reduce((prev, curr) => prev + curr.qty, 0),
  };
});

console.dir(result, { depth: null, color: true });

Check out

Answer №3

function updatedList(data) {
    return data.map(item => ({
        ...item,
        ...modifyData(item.data)
    }));
}

function modifyData(arr) {
    return arr.reduce((acc, cur) => {
        acc.data = acc.data || [];
        acc.total = acc.total || 0;
        if (!acc.data.some(elem => cur.id === elem.id && cur.quantity === elem.quantity)) {
            acc.data.push(cur);
            acc.total += cur.quantity;
        }
        return acc;
    }, {});
}

var data = [
    { id: 1, data: [{ id: 1, quantity: 1 }, { id: 2, quantity: 2 }, { id: 2, quantity: 2 }], code: "alpha", total: 1 },
    { id: 2, data: [{ id: 3, quantity: 2 }, { id: 4, quantity: 2 }], code: "beta", total: 2 }
]

console.log(JSON.stringify(updatedList(data)));

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

"Securing Your Web Application with Customized HTTP Headers

I'm currently working on setting up a POST request to a REST API (Cloudsight) with basic authorization. Here is the code I have so far: var xhr = new XMLHttpRequest(); xhr.open("POST", "http://api.cloudsightapi.com/image_requests", true); xhr.setRequ ...

Is there a way for me to direct to a different HTML page once I click on a certain data point?

At the moment, I have been utilizing this complete set of calendar codes. <!DOCTYPE html> <html> <head> <meta charset='utf-8' /> <link href='fullcalendar.css' rel='stylesheet' /> <link href=&a ...

Adjusting the dimensions of a Java array

Can the number of dimensions in an array be altered, such as creating it like this int[][] i = new int[3][3]; but utilizing it like this getArray(i); //where getArray only accepts one dimensional arrays ? ...

vue-dropzone fails to create thumbnails when a file is added

I am facing an issue where I want to upload files that are already stored on my server to the Dropzone. Despite searching extensively through both vue-dropzone and regular dropzone documentation, as well as various GitHub issues for solutions, I have not b ...

Sending color data to fragment shader in JavaScript

I've recently started learning webgl and have a query. I'm attempting to construct a triangle and send the color data to the fragment shader from a js file. Below is my js code: var VSHADER_SOURCE = 'attribute vec4 a_Position;\n&ap ...

Importing JS files or SDKs in Angular that are not modules

Currently, I am incorporating the Avaya SDK (which consists of 3 JS files) into my Angular project. However, when attempting to import it, I encounter an error stating that it is not recognized as a module. Any suggestions on how to resolve this issue? Th ...

The video is not appearing on mobile devices using Safari, Firefox, and Chrome, but it is displaying properly on desktop computers

My website has a video in the header that works fine on desktop but not on mobile. I am using next.js 13.4 and here is my code: <video id="background-video" autoPlay playsInline loop muted classN ...

'Encountering error message "Attempting to access property of non-object" when attempting to prepend an element to an array using

In my possession, I hold an array: $data = '[{"NO":"1","ID_JPS":"AAA"},{"NO":"2","ID_JPS":"BBB"}]'; $data_ori = json_decode($data); Within a for loop, I am extracting the properties NO and ID_JPS. for($i=0; $i < count($data_ori); $i++){ ...

How can I correctly update values from a sibling component that has been imported in Vue.js 2.0?

My Vue 2.0 project follows the single-file component approach and consists of three components: App (parent), AppHeader, and FormModal. Both AppHeader and FormModal are direct children of App and siblings of each other. The main objective is to toggle the ...

The functionality of ng-table appears to be compromised when working with JSON data

Currently, I am facing an issue while using a JSON file to populate data in my Angular ng-table. Even though the JSON data is being displayed in a regular table format, certain functionalities of ng-table like pagination and view limit are not functioning ...

A Guide to Building Arrays with User Input using Scanner in Java

I need help creating a method that can print out an array based on user input using the Scanner class. The array should contain double data types. Currently, I have successfully initialized an array with the size provided by the user. My question is how ...

Make sure a div is displayed on top of any content currently in fullscreen mode

I recently encountered an issue with my Chrome extension where a menu I inserted into the page would disappear whenever a flash or html5 video player went full screen. Is it possible to have two objects in full screen simultaneously, or is there another so ...

Storing customer information securely on the server with the help of Node.js

After spending some time experimenting with Node.js on my local machine, I've realized that my understanding of HTTP requests and XHR objects is quite limited. One particular challenge I've encountered while using Node is figuring out how to effe ...

Express.js syncing with Backbone.js using only POST and GET requests

My application utilizes Backbone.js on the client-side and Express.js on the back-end. I am facing challenges when it comes to syncing all parts of my API by utilizing the backbone model and collection, which are configured with urlRoot: "/users". I am re ...

Before I press enter, what kind of function is evaluated by the Node.JS REPL?

It's interesting how in the Node.JS REPL, the result of the current expression sometimes gets evaluated before hitting enter, which raises questions. I find it puzzling: How does Node.JS determine if I intended to evaluate it or not? Simple calculati ...

"Exploring ways to retrieve the initial element from an array within a hash value

I have a dictionary with song titles as keys and their lyrics as values, stored as arrays. Code: class Song def initialize(lyrics_dict) @lyrics = lyrics_dict end def display_song_names() puts @lyrics.keys end def get_fi ...

Is there a way to remove a Google task from the Google Task queue using Node.js programmatically?

Is there a way to remove a task from Google Task queue programmatically using Node.js? The information provided in the documentation does not address how this can be done in Node.js. You can access the task queue through this Task Queue Link. ...

Is there a way to smoothly navigate back to the top of the page after the fragment identifier causes the page to scroll down?

I do not want to disable the functionality of the fragment identifier. My goal is for the page to automatically scroll back to the top after navigating to a specific section. This inquiry pertains to utilizing jQuery's UI tabs. It is crucial to have ...

Is it possible to create a CSS-only solution that can adapt variable content to a vertical grid without using JavaScript?

I am currently facing a minor issue with a website I am working on that, while not a major problem, would be great to resolve. The site, including all promotional materials for the event it represents, has been designed based on a precise square grid. Ever ...

The retrieval of a single item from a Firestore database using a POST request is experiencing issues

I have set up a Firestore application which currently has a collection named 'students' with 5 documents. One of those documents is assigned the id: 1 Using an HTML form, I am able to add individual students to this collection. Additionally, I&a ...