Inserting duplicate rows from CSV using JavaScript

Currently, I am utilizing Papaparse to sum up rows with duplicate SKUs in my CSV file. I'm striving to achieve this task without the use of additional JS libraries such as D3. Here is a snippet of how my CSV data is structured:

SKU,Daily total,Weekly total
AAA111,2,10
BBB222,4,6
CCC333,11,19
AAA111,5,11
BBB222,6,12

Although I have successfully displayed all rows from the table, I am aiming to dynamically combine rows with identical SKU numbers together.

    <script>
        function datasetToMap(data) {
        var ret = {};
        $(data).each(function(index, row) {
            ret[row] = row;
        });
           
    return ret;
}

function appendMapToTable(map) {
    var $table = $('#my-table');
    Object.keys(map).forEach(function(key, i) {
        var rowData = map[key];
          var row = $('<tr class="rownum-' + [i] + '"></tr>');
      $(rowData).each(function (j, cellData) {
        row.append($('<td class="' + [j] + '">'+ cellData +'</td>'));
    });
      $table.append(row);
  });
}

$.ajax({
    type: "GET",
    url: "https://cdn.shopify.com/s/files/1/0453/8489/t/26/assets/testcsv.csv",
    success: function (data) {
        appendMapToTable(datasetToMap(Papa.parse(data).data));
    }
});

I aim to display AAA1111 with totals of 7 and 21, while BBB222 will show totals of 10 and 18 in the table.

A live demonstration can be found at: https://codepen.io/BIGREDBOOTS/pen/LjmojW

Answer №1

Below is a creative ES6 approach that utilizes a hash for storing SKU values and a reduce function to combine daily and weekly totals:

const data = `SKU,Daily total,Weekly total
AAA111,2,10
BBB222,4,6
CCC333,11,19
AAA111,5,11
BBB222,6,12`

// excluding the header row and converting strings to numbers
const rows = data.split('\n').slice(1).map((row) => {
   return row.split(',').map(i => !isNaN(Number(i)) ? Number(i) : i)
})

const aggregate = rows.reduce((p, row) => {
  let [sku, dayTotal, weekTotal] = row
  if (p[sku]) {
    let [_, prevDayTotal, prevWeekTotal] = p[sku]
    p[sku] = [sku, prevDayTotal + dayTotal, prevWeekTotal + weekTotal]
  } else {
    p[sku] = [sku, dayTotal, weekTotal]
  }
  return p
}, {})

console.log(aggregate)

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

Extracting a precise data point stored in Mongo database

I have been struggling to extract a specific value from my MongoDB database in node.js. I have tried using both find() and findOne(), but I keep receiving an object-like output in the console. Here is the code snippet: const mongoose = require('mongoo ...

Issues encountered when attempting to append the array objects to HTML using $.getjson

Hello, I have a JSON data structure as shown below: [{ "menu": "File", }, { "menu": "File1", }] I have created jQuery code to dynamically add the response to my HTML page like this: $(document).ready(function () { $.getJSON('data.json&a ...

What could be causing the pageLoad function on certain ASP.net pages to not fire for my user control?

Currently, I am developing an ASP.net application. A user control that I created called LocationSelector was working perfectly. However, I encountered an issue when trying to use it within an ASP:UpdatePanel. After researching on SO, I realized that movin ...

What steps should I take to ensure my mineflayer sprints while trailing behind me?

I am developing a Mineflayer bot that follows me and tries to attack me. However, when I move far away from the bot, it stops following me. In addition, the bot has another issue where it falls while bridging due to its lack of intelligence. How can I im ...

Having difficulty drawing an arrow connecting one mesh object to the surface of another mesh object

When attempting to draw an arrow from one mesh object to another, I encountered some issues. Directly using the positions of the objects as arguments in the Arrow Helper resulted in the arrow going inside the object due to the position representing the cen ...

"Error encountered in @mui/x-data-grid's ValueGetter function due to undefined parameters being passed

I'm currently using @mui/x-data-grid version 7.3.0 and I've encountered a problem with the valueGetter function in my columns definition. The params object that should be received by the valueGetter function is showing up as undefined. Below is ...

Generating variables dynamically within a React Native component

In my React Native component, I need to create a variable that will be used multiple times. Each instance of this component should have a different variable name for reference. <View ref={view => { shapeView = view; }} onLayout={({ nativeE ...

Sending an Array from JavaScript to Asp.net Core

Below is the javascript code that invokes the asp.net CustomHeatMapDate function $('.Date').change(function () { var data = []; console.log(); var dateList = [{"Date":"03/23/2016"}, {"Date":"03/24/2016"}]; $.ajax({ async: ...

Tips for receiving notifications when the Collapsible collapses

I'm having trouble figuring out how to receive notifications when the Collapsible is expanded and collapsed. Currently, I am not receiving any type of notification. Any suggestions on how to make this work? Below is my code: --Imported jQuery < ...

Website experiences technical difficulties but database remains up-to-date

I previously made a similar post, but I have not resolved the issue yet. Here is the output from my terminal: 23 Dec 22:31:23 - Serving request for url[GET] /team 23 Dec 22:31:23 - Successfully created team with Name : Japan 23 Dec 22:31:23 - Serving re ...

Having trouble retrieving properties from a JavaScript JSON object?

I am currently working with a JSON object that contains properties for MAKEs, MODELs, YEARs, STATEs, PLATEs, and COLORs. There are 4 instances of each property within the object: Object {MAKE1="xxx ", MODEL1='xxx', YEAR1='xxx', STATE1= ...

unable to retrieve element values using class names

I have created multiple h1 elements with the same class names listed below. <h1 class="h1">One</h1> <h1 class="h1">Two</h1> <h1 class="h1">Three</h1> <h1 class="h1">Four</h1> I have also added a button that ...

A tiny blue spot popping up beside the roster of users

I'm working on a render function that displays a list of users with avatars and names. The issue I'm facing is that when the page initially loads, there's a blue dot to the left of each user. However, if I navigate to another page and then g ...

Is there a way to retrieve and gather all data from various scopes and then access them collectively?

I attempted to scrape information from a website using Node.JS + Cheerio + Axios. I was able to retrieve all the necessary data, but encountered an issue with returning the data from different scopes in order to receive it. Currently, I can only obtain the ...

Enhancing the AngularJS Login feature for server authentication

Struggling to adapt Valerio Coltrè's Angular login example on GitHub to work with my ServiceStack authentication. Despite appreciating Valerio's implementation of authentication, I am facing challenges as he uses an httpBackend mock and interce ...

Understanding how to decode querystring parameters within a Django view

In the application I'm working on, there is a search form that utilizes a jQuery autocomplete plugin. This plugin processes the querystring and sends back the suggested item using encodeURI(q). For example, an item like Johnny's sports displays ...

Is there a way to verify that all images have been successfully loaded following an

Is it possible to determine when all images have finished loading from an appended HTML source in order to trigger another function? $(document).ready(function () { $('a.load-more').click(function (e) { e.preventDefault(); $.ajax({ ...

fetching a set of data entries from an entity on dynamic CRM platform utilizing the REST API along with asynchronous JavaScript and XML

Seeking to display all accounts from the account entity in an alert box by making an ajax call to the Service OrganizationData.svc. The post method works fine for adding an account, but when trying to retrieve all accounts using GET, I encounter some diff ...

When attempting to click on my subtopics using jQuery, they do not appear as expected

$(document).ready(function () { $("#subTopics").hide(); $("#mainTopics").click(function () { $("#subTopics").show("slow"); }); }); body { margin: 0; } li, a{ text-decoration: none; list-style-type: none; text-d ...

Is an external source compatible with Jquery autocomplete/combobox?

Searching for a selectbox autocompleter that mimics the functionality of a combobox, where if a value does not exist it returns false/null. http://jqueryui.com/demos/autocomplete/#combobox Is there a method to integrate an external datasource with the co ...