javascript
javascript
javascript
  • Lấy vị trí người dùng với javascript
  • [Problem] Lấy key đầu tiên tìm thấy chứa giá trị cần tìm (ok)
  • 🥸Đoạn mã JavaScript để thêm ký tự đặc biệt vào đầu mỗi dòng trong văn bản nhiều dòng (ok)
  • 😍Tạo ra font in đậm và copy đến website để sử dụng (ok)
  • Hiệu ứng mở sách cực đẹp
  • 🤩JS: Scroll Animation using Intersection Observer API 🤩 (ok)
  • 😅Draw svg on scroll Full (ok)
  • 😄Install Linguise on any domain dịch tự động (ok)
  • 😅Sử dụng ajax tạo popup cho các bài viết wordrpess mattervn.com (ok)
  • 😆PWA - beforeinstallprompt toplusgames.com (ok)
  • How to Use the HTML5 Full-Screen API (Again) (ok)
  • [ERROR GAME] fix lỗi không load iframe gamedistribution.com for toplusgames.com (ok)
  • 😅jQuery Plugin To Create Animated Placeholders - placeholderTypewriter (ok)
  • 😍Làm chức năng thông báo khách hàng đăng ký namkhoahanoi.vn (ok)
  • Tencent Captcha Demo (ok)
  • 😉Send Mail same javascript elasticemail (ok)
  • 🥳Các tool phong thuỷ (ok)
  • 😇Nice Select A lightweight Vanilla JavaScript plugin (ok)
  • Merge objects with the same id but sum values of the objects (ok)
  • 😅Page: DOMContentLoaded, load, beforeunload, unload phần 1 (ok)
  • 😍Scripts: async, defer phần 2(ok)
  • 😂Javascript Array chunkArrayInGroups(arr, size)
  • Sequentially Resolve Promises Works, Giải quyết tuần tự các lời hứa hoạt động (ok)
  • Using Async / Await with the Array Reduce Method API (ok)
  • Flatten an array of arrays,merge, làm phẳng một mảng các mảng (ok)
  • 😌Dependent Dropdown Full (ok)
  • 🥳Select Box Change Dependent Options dynamically (JavaScript Object)
  • 🤩Add elements dynamically full (ok)
  • 😅👌Multiple versions jquery (ok)
  • 😍Cách sử dụng jQuery trong sweetAlert2 là chúng ta phải sử dụng didOpen full (ok)
  • 😁😁 mdbgo.io, mdbootstrap.com full (ok)
  • 🤪Chú ý nếu lỗi cảnh báo từ khóa new nếu dùng trong js thường chúng ta sẽ sử dụng trong mudule (ok)
  • 😝reCAPTCHA javascript (ok)
  • Firework Simulator v2 Phao Hoa (ok)
  • Active scroll center (ok)
  • 🤪Sort array of objects by string property value (ok)
  • 😏findIndex, find index in Array object (ok)
  • 😂Sử dụng nhiều toán tử 3, multiple Ternary Operators (ok)
  • 😅A simple and easy to use library that creates fullscreen scrolling websites fullPage.js (ok)
  • Xây dựng ứng dụng CRUD sử dụng Vue.js trong Laravel (ok)
  • [Chart] Morris.js Line & Area Charts,Bar Charts, Donut Charts, graph (ok)
  • [Chart] Chart.js
  • Multi select checkbox table bootstrap (ok)
  • 😀jquery new, jquery old, jquery migrate (ok)
  • Popup slide up from the bottom overflowing other div blocks (ok)
  • ASYNC JavaScript (CALLBACK, PROMISES, ASYNC AWAIT) video (ok)
  • === START jQuery Mobile ===
  • Data Attributes full (ok)
  • Viết một ứng dụng Restaurant Picke sử dụng "back menu" (ok)
  • Viết một ứng dụng thời tiết, Weather sử dụng panel (ok)
  • jQuery Mobile Tutorial w3schools.com (ok)
  • jQuery Mobile
  • jQuery Mobile - Events (ok)
  • Back button in jquery mobile (ok)
  • === END jQuery Mobile ===
  • removeDuplicates, Remove duplicate values from JS array, remove all duplicates an array object (ok)
  • Sử dụng thư viện jquery.hoverdir.js để làm hiệu ứng hover tuyệt đẹp (ok)
  • Modernizr là gì ? Sử dụng nó cho những trình duyệt cũ ra sao? (ok)
  • Nhận biết tính năng CSS: Modernizr hay Feature Queries? (ok)
  • [SALESFORCE] Remote Action function in Visualforce Page (ok)
  • ScrollIt.js menu (ok)
  • Cách sử dụng scrollTo vanilla cực chất 😘 (ok)
  • Một bài toán xử lý bất đồng bộ trong kintone để lấy số requet quá giới hạn (OK)
  • hexagon thư viện tạo avatar Canvas (ok)
  • 😅Sử dụng Object.assign và để copy dữ liệu, edit, input, form (ok)
  • Một cách đặt và gán giá trị trong mảng, object cự ngắn gọn (ok)
  • [LAZY] jQuery.Lazy và tạo background-loading cực chất (ok)
  • Ví dụ Sử dụng sẵn thư viện masonry của wordpres (ok)
  • Ảnh base64 dùng làm src, placeholder (ok)
  • Kiểm tra hình ảnh đã được tải với thư viện imagesLoaded (ok)
  • Check if Function Exists before Calling? (ok)
  • Async/Await Javascript Full Example (ok)
  • Thenables in JavaScript phục vụ cho bài viết trên (ok)
  • Script distance, khoảng cách (ok)
  • Time, Date full (ok)
  • Function getAllDatesOfMonth (ok)
  • How do I make a placeholder for a 'select' box? (ok)
  • Library choise (ok)
  • jQuery - Redirect with post, Get data php (ok)
  • How to pass data from one page to another page html (ok)
  • how to send data onClick() to another php for processing using post or get?
  • draw grid, vẽ grid (ok)
  • Fullscreen Horizontal Page Slider with jQuery and CSS3 - HSlider scroll template html (ok)
  • _.template, UnderscoreJS Templates Full (ok)
  • Character limit on tag type input number (ok)
  • How to set maximum length in input type=number (ok)
  • ========= START JEST =======
  • Getting Started (ok)
  • Using Matchers (ok)
  • Testing Asynchronous Code
  • Setup and Teardown (ok)
  • Mock Functions
  • Jest Platform
  • Jest tutorial
  • Testing trong Javascript với Jest (Phần 1) (ok)
  • Testing trong Javascript với Jest (Phần 2)
  • Giới thiệu về Jest (Delightful JavaScript Testing)
  • Thử nghiệm phát triển theo hướng phản ứng với Jest và Enzyme
  • Cách kiểm tra các thành phần phản ứng với Jest và Enzyme, Phần 1
  • Cách kiểm tra thành phần phản ứng với Jest và Enzyme, Phần 2
  • Jest js mock jquey and lib
  • Unit testing Các thành phần React với Enzyme và Jest
  • Hướng dẫn viết unit test React với Jest và Enzyme (P1)
  • Tôi đã test các React component như thế nào? (phần 2)
  • Test component trong React với Jest
  • Test Component với Jest và Emzyme
  • Tổng quan về unit test cho dự án react redux saga với Jest Part 1
  • ========= END JEST =======
  • ======= START GULP TUTORIAL ======
  • [GULP] Tìm hiểu về Gulp.js
  • [GULP] Gulp Tutorial
  • [GULP] Gulp - Developing An Application (ok)
  • [GULP] Gulp - Combining Tasks (ok)
  • [GULP] Gulp - Watch (ok)
  • [GULP] Gulp - Live Reload
  • [GULP] Gulp - Optimizing CSS and JavaScript
  • [GULP] Gulp - Optimizing Images
  • [GULP] Gulp - Useful Plugins
  • [GULP] Gulp - Cleaning Unwanted Files
  • Đọc thêm những tài liệu trang khác
  • ======= END GULP TUTORIAL ======
  • Prevent form submission on Enter key press, keyCode (ok)
  • Lấy kích thước ảnh gốc image (ok)
  • 😆How to Center Carousel Slider (ok)
  • Putting Dots onto Owl Carousel Instead of below specialtouchgifts.com.au (ok)
  • Cách xây dựng một Full Screen Carousel với Owl.js
  • Lazy load với owl.carousel.js (ok)
  • Show half of the other item on Owl Carousel vinmec.com items: 1.5 (ok)
  • Show half of the other item on Owl Carousel vinmec.com stagePadding (ok)
  • ------------ Start Fetch -----------
  • Using Fetch Full
  • 😅Javascript Fetch JSON PHP Complete FormData phần 1(ok)
  • Một ví dụ quá đỉnh lấy dữ liệu của form submit trong js bằng đối tượng new FormData + php phần 2(ok)
  • Có một sự thật sử dụng async đồng nghĩa với trả về kết quả là PROMISE (ok)
  • 😅Promise.all full (ok)
  • All you need to know about Promise.all
  • [PROMISE] Promise.all()
  • [PROMISE] Tìm hiểu về promise trong ES6
  • [PROMISE] Introduction to Promises
  • jQuery off() Method (ok)
  • How to make HTTP requests with Axios
  • Axios vs Fetch - 2020 nên sử dụng thằng nào với những tính năng mới trong javascript
  • Get and Post method using Fetch API (ok)
  • Sử dụng JavaScript Fetch API với Async/Await (ok)
  • Xử lý lỗi cho fetch trong trường hợp không có kết nối hoặc kết nối lâu (ok)
  • ------------ End Fetch -----------
  • BigDataCloud Free Reverse Geocoding Javascript API Client (ok)
  • Vietmap API
  • 🥰Sử dụng API Giao hàng Nhanh để tính giá cước vận chuyển (ok)
  • photonsearch as you type with OpenStreetMap map (ok)
  • Leaflet - Một thư viện JS mã nguồn mở cho việc xây dụng ứng dụng bản đồ map (ok)
  • Xây dựng popup lấy vị trí map áp dụng pointfinder (ok)
  • Reverse Geocoding Convert Lat Long to Address map (ok)
  • Free Reverse Geocoding Javascript API map (ok)
  • [YAML] In Action Tutorial Series - General - Hướng dẫn sử dụng file YML YAML cơ bản
  • ----------------- Start Notification -----------------
  • Đối tượng caches object caches (ok)
  • Notification (ok)
  • Sử dụng indexedDB (ok)
  • Using the Notifications API (ok)
  • NotificationEvent (chưa có ví dụ :((
  • ServiceWorkerGlobalScope.onnotificationclick (ok)
  • ServiceWorkerRegistration.getNotifications(ok)
  • ServiceWorkerRegistration.showNotification(ok)
  • Giao tiếp giữa các cửa sổ với Window.postMessage API (ok)
  • Window open() Method (ok)
  • ----------------- End Notification -----------------
  • Example Cookie full (ok)
  • Thay đổi class active javascript bằng cách viết hàm (P1)
  • Thay đổi class active javascript bằng cách viết hàm (P2)
  • jQuery Mockjax Plugin (chưa học cách sử dụng)
  • jQuery Ajax X-editable bootstrap plugin (chưa học cách sử dụng)
  • Lọc theo điều kiện (filter) (ok)
  • Các ví dụ về filter
  • jQuery | grep() Method (ok)
  • Hai bài toán so sánh kinh điển trong javascript
  • Function random :)
  • Một cách sử dụng tab trong theme newspaper
  • Hiệu ứng scroll + animation + menu trượt mượt
  • Trigger a CSS animation on scroll xuongkhopbacninh.vn (ok)
  • App Css Loaded (scroll create link) (ok)
  • Hiệu tứng scroll cực chất (ok)
  • App Js Loaded (ok)
  • Sử dụng async và defer full (Oke)
  • Cách sử dụng Thuộc tính async và defer trong JavaScript hay
  • ReferenceError: Can't find variable: requestAnimationFrame
  • Đoạn code check lỗi PHP trong Ajax
  • [SELECT2] Sử dụng Select2 để thay thế select boxes
  • Một cách sử dụng lazyload khi addclass thật khó khăn...
  • Hiệu ứng croll chuột và % cực đẹp :_
  • Tạo chức năng tự động hoàn tất nhập liệu với thư viện jQuery UI Autocomplete (Phần 1)
  • Tạo chức năng tự động hoàn tất nhập liệu với thư viện jQuery UI Autocomplete (Phần 2)
  • JavaScript String split() Method (OK)
  • Sử dụng thư viện displace để làm menu kéo thả (ok):)))
  • Menu cực chất :)))
  • Sử dụng thư viện slick (ok)
  • vertical scroll, Vertical carousel (ok)
  • Google-like Thanos disintegration (ok)
  • Dùng thư viện jspdf
  • Công thức Toán học cho website
  • Fix lỗi tự động làm thay đổi độ cao :( vieclam123.vn :(
  • Sử dụng window.addEventListener để resize và responsive <3
  • Javascript create, read, and delete cookies (ok)
  • Tự động submit bằng javscript :))) (ok)
  • avoid form warning if user clicks refresh (ok)
  • Một cách truy cập phần tử bằng js thông qua id lạ :)))
  • Meta Refresh
  • Truyền dữ liệu từ javascript sang php
    • Sử dụng form để truyền sang php (ok)
    • Truyền giá trị theo file bằng đường dẫn (ok)
    • Dùng json để truyền sang php
  • auto-refresh page once only after first load – Using JavaScript / JQuery
    • auto-refresh page once only after first load – Using JavaScript / JQuery (ok)
  • Sticky Scroller
    • Sticky Scroller phần 1 (ok)
    • Sticky Scroller phần 2 (ok)
    • owl carousel with dotsContainer (Dots + Text) (ok)
    • Owl Carousel 2 Thumbnails plugin (ok)
  • easy_background Background Slideshow (ok) dev.vieclam123.vn
  • scroll cực chất timviec365.vn, vieclam123.vn (ok)
  • Thư viện lightslider-master gần giống với Owl Carousel
  • Thư viện lightGallery để làm những bộ Sưu tập Gallery
  • Tự viết click slide (ok)
  • Draggable & Touch-friendly Slider Carousel In Pure JS (ok)
  • Slider owl được viết dưới dạng Thumnail (0k)
  • jquery.js:5092 [Violation] Added non-passive event listener to a scroll-blocking 'touchstart' (ok)
  • Added non-passive event listener to a scroll-blocking 'touchstart' event (ok)
  • sticky-mobile-menu-burger-menu (ok)
  • How can I add class to the first and last item among the visible items of Owl Carousel 2? (ok)
  • Owl-carousel2 DEMO - items in 2 rows (oke)
  • How can I create a carousel slick with multiple rows? (ok)
  • Một cách sử dụng create <style> để thêm style (ok)
  • Two Rows Olw Carousel (ok) vieclam123.vn
  • Chức năng tự gọi Javascript (ok) tự động auto
  • Click Next Javascript Base (ok)
  • Slider owl được viết dưới dạng Thumnail viết trên jsfiddle (0k)
  • 😆Creating a Countdown Timer, dakhoathienhoa.com.vn (oK)
  • 🥸NumScroller, Counter From Zero To Value - Javascript Animation (ok)
  • Click Button background-hover white (ok)
  • CodePen HomeLazy Loading Images (Ok)
  • Custom Date Javasript (job247.vn)
  • Tooltip
  • button thay đổi thẻ tags button và span trong Owl Carousel thành thẻ khác :)) (ok)
  • Thêm class vào navigation Owl Carousel (ok)
  • Click lần đầu sử event.preventDefault(); lầu sau not event.preventDefault();
  • landscape && landscape (ok)
  • Landscape && Portrait (ok) job247.vn
  • Hammer thư viện JavaScript chạm cho màn hình cảm ứng
  • jQuery Plugin To Add CSS3 Scrolling Effects On Your Web Page - Smoove menu (ok)
  • 😃Auto Expanding Table Of Contents Plugin - Dynamic Content menu (ok)
  • Tornis - watch and respond
  • scroll-manager
  • Xem thêm
  • Hướng dẫn nấu món "Lazy loading image" theo chuẩn 5 sao Google
  • Welcome to jquery-confirm!
    • jQuery Message Box Plugin Demo Page
  • Magnific-Popup Popup img
  • Slider Swiper Slider-Swiper dùng viết slider giống app
  • Magnific Popup Documentation
  • filter search (ok)
  • Is it possible to convert a select menu to buttons? (ok)
  • Changing selected option on button click select (ok) homef.vn hoặc inop.vyanh.net
  • scrooll animation (job247.vn) (ok)
  • Select2 tutorial
    • Single select boxes (ok)
  • [SELECT2] Disabling a Select2 control (ok)
  • Disabling options (ok)
  • placeholder (ok)
  • Hiển thị nút xóa các giá trị đã chọn + allowClear (ok)
  • Đọc dữ liệu từ một mảng, Data sources (ok)
  • Sử dụng database + php (ok)
  • [SELECT2] Sử dụng form + select2 + ajax + get value (ok)
  • Đọc dữ liệu từ nguồn khác sử dụng AJAX (ok)
  • Thiết lập giá trị mặc định ban đầu trên HTML như bình thường (ok)
  • Sử dụng Ajax để tải dữ liệu từ một nguồn khác (ok)
  • change form
Powered by GitBook
On this page
  • Merge objects with the same id but sum values of the objects
  • 2 Answers
  • How to sum the array of object values and assigned them to the relevant key name
  • How to sum the array of object values and assigned them to the relevant key name
  • 4 Answers

Was this helpful?

Merge objects with the same id but sum values of the objects (ok)

https://stackoverflow.com/questions/44332180/merge-objects-with-the-same-id-but-sum-values-of-the-objects

PreviousNice Select A lightweight Vanilla JavaScript plugin (ok)NextPage: DOMContentLoaded, load, beforeunload, unload phần 1 (ok)

Last updated 2 years ago

Was this helpful?

Asked 5 years, 7 months agoModified Viewed 3k times1

I want to reduce my array of objects by comparing previous and current object from the array, if the id of previous object is different then current object, then I write the previous object to my result list and override it with the current object else I sum the values of both objects. In the end it should be a reduced array, no duplicates.

I have data like this:

[{
    Clicks: 210,
    Company: "A",
    _id: { CompanyID: 5 }
},
{
    Clicks: 35,
    Company: "C",
    _id: { CompanyID: 3 }
},
{
    Clicks: 15,
    Company: "B",
    _id: { CompanyID: 2 }
},
{
    Clicks: 13,
    Company: "A",
    _id: { CompanyID: 5 }
}]

And want to reduce it to this form:

[{
    Clicks: 223,
    Company: "A",
    _id: { CompanyID: 5 }
},
{
    Clicks: 35,
    Company: "C",
    _id: { CompanyID: 3 }
},
{
    Clicks: 15,
    Company: "B",
    _id: { CompanyID: 2 }
}]

Here is my not correctly working solution so far:

$scope.reduce = function () {
    var result = [];
    var prev = null;

    angular.forEach($scope.data, function (value, key) {
        if (prev != null) {
            if (prev._id.CompanyID != value._id.CompanyID) {
                result.push(prev);
                prev = value;
            } else {
                prev.Clicks += value.Clicks;
            }
        } else {
            prev = value;
        }
    });
}

My result looks good, it reduce all duplicates but it does not sum the values of objects with the same ids, it just overrides the ids with the last object.

2 Answers

Sorted by: Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 5

You can use thisArg parameter in forEach loop and pass a empty object to store values.

var data = [{"Clicks":210,"Company":"A","_id":{"CompanyID":5}},{"Clicks":35,"Company":"C","_id":{"CompanyID":3}},{"Clicks":15,"Company":"B","_id":{"CompanyID":2}},{"Clicks":13,"Company":"A","_id":{"CompanyID":5}}];
var result = [];

data.forEach(function(obj) {
  var id = obj._id.CompanyID
  if(!this[id]) result.push(this[id] = obj);
  else this[id].Clicks += obj.Clicks;
}, Object.create(null));

console.log(result);
var data = [{ Clicks: 210, Company: "A", _id: { CompanyID: 5 } }, { Clicks: 35, Company: "C", _id: { CompanyID: 3 } }, { Clicks: 15, Company: "B", _id: { CompanyID: 2 } }, { Clicks: 13, Company: "A", _id: { CompanyID: 5 } }],
    result = data.reduce(function (hash) {
        return function (r, a) {
            var key = a._id.CompanyID;
            if (!hash[key]) {
                hash[key] = { Clicks: 0, Company: a.Company, _id: a._id };
                r.push(hash[key]);
            }
            hash[key].Clicks += a.Clicks;
            return r;
        };
    }(Object.create(null)), []);

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

I need to understand the simplest way of doing this. I've got an array of objects:

const data = [
  {
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
]

What I'm trying to get is simple object where its key is the month from data.incomes and the value is sum of relative month values, so the final result looks like:

const totalIncomes = {
  "2019-12": 125,
  "2020-12": 250,
  "2021-12": 15
}

Can anybody explain it to me step by step, please?

4 Answers

Sorted by: Highest score (default) Trending (recent votes count more) Date modified (newest first) Date created (oldest first) 3

solved using reduce and forEach

Inside the reduce function I'm running a forEach on the array of keys of the incomes object/attribute. For each key which is a date I'm checking if the accumulator of the reduce function contains an attribute for each date and creates if not. After creating the attribute I'm summing the value for the current date attribute.

const data = [{
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
]

const totalIncomes = data.reduce((acc, curr) => {
  Object.keys(curr.incomes).forEach((key, index) => {
    if (!acc[key]) {
      acc[key] = 0
    }
    acc[key] += curr.incomes[key]
  })
  return acc
}, {})

console.log(totalIncomes)

Maybe this is not the pretties solutions but you can do it like this, the function is of course not necessary.

const data = [
  {
    group: "A",
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15,
    },
  },
  {
    group: "B",
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    },
  },
];

getterInformation(data);

function getterInformation(object) {
  let objectWithCalculatedValues = {};

  object.forEach((items) => {
    for (const key in items.incomes) {
      if (objectWithCalculatedValues[key] === undefined) {
        objectWithCalculatedValues[key] = 0;
      }

      objectWithCalculatedValues[key] += items.incomes[key];
    }
  });

  console.log(objectWithCalculatedValues);
}

Assuming that this information may be useful to readers who may be unable to obtain necessary guidance (due to various possible reasons), here is one possible way to achieve the objective (solution):

const aggregateIncomesByMonth = () => (
  data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
    key: k,
    value: v
  }))).flat().reduce((fin, itm) => ({
    ...fin,
    [itm.key]: (fin[itm.key] || 0) + itm.value
  }), {})
);

Explanation

  1. Extract only the incomes from the data array

  2. For each income object, get the key-value pair and transform into another object of the structure {key: 20yy-mm, value: nn}

  3. Use .flat() to transform the result from step-2 into a 1-dimensional array

  4. Use .reduce to sum the value for those cases where the key (ie, 20yy-mm) matches.

Code-snippet

const data = [{
    group: 'A',
    incomes: {
      "2019-12": 100,
      "2020-12": 200,
      "2021-12": 15
    }
  },
  {
    group: 'B',
    incomes: {
      "2019-12": 25,
      "2020-12": 50,
    }
  }
];

const aggregateIncomesByMonth = () => (
  data.map(d => Object.entries(d.incomes).map(([k, v]) => ({
    key: k,
    value: v
  }))).flat().reduce((fin, itm) => ({
    ...fin,
    [itm.key]: (fin[itm.key] || 0) + itm.value
  }), {})
);

console.log(aggregateIncomesByMonth());

My approach here is to destructure the array. This way I have all the data of the incomes of group A in the variable A and the same for B.

Then I do a double loop to compare both objects data and see if the dates match. If so, sum the incomes and add the data to the total object.

const data = [
  {
    group: 'A',
    incomes: { "2019-12": 100, "2020-12": 200, "2021-12": 15 }
  },
  {
    group: 'B',
    incomes: { "2019-12": 25, "2020-12": 50 }
  }
]

let A, B, total = {};

[A, B] = [data[0].incomes, data[1].incomes]

for(const date in A){
  for(const d in B){
   total[date] = date === d ? A[date] + B[date] : A[date]
  }  
}

console.log(total)

Follow16.7k44 gold badges8181 silver badges125125 bronze badgesasked Jun 2, 2017 at 15:1210933 silver badges1313 bronze badges

Run code snippetExpand snippetFollow16.7k44 gold badges8181 silver badges125125 bronze badgesanswered Jun 2, 2017 at 15:19116k1515 gold badges146146 silver badges169169 bronze badges

Thanks for you help. I actually wanted to know what my mistake was. I already found out what i did wrong, i have logic error, because i reference to my first object instead of doing a deep copy. And your code is somewhat irritating by using the keyword this. I think it is not good to use this in javascript, specially here. :) –

I think it is not good to use this in javascript why is that? –

In your example "this" is irritating, but it works fine, but not a good design from my point. It is not clear what "this" actually is. So for me and a lot of other developer will agree that "this" can be confusing ("this" in object scope or object's function scope?) and bring inconsistent behavior. Here is how i changed your code: –

4

For a version with , you could use a hash table as reference to the same company with a closure over the hash table.

Asked 12 months agoModified Viewed 3k times2

Followasked Jan 20, 2022 at 16:5233711 gold badge33 silver badges1414 bronze badges

Run code snippetExpand snippetFollowanswered Jan 20, 2022 at 16:575,0883333 gold badges4141 silver badges5151 bronze badges

1Thanks a lot! I tried to do almost the same using Object.entries() not Object.keys and that was where I had an error coming from. –

1@cmgchess this answer can be improved by adding some useful explanation... –

1@Gass i was in a hurry. added some explanation –

1

Followanswered Jan 20, 2022 at 17:118911 silver badge33 bronze badges

Maybe it's not the prettiest on but it's working and it's also easy for me to understand so it's absolutely fine.👍 Thank you. –

@Galterius you can improve it easily by reducing the length of your variable names. They should be descriptive but not that much ;) –

1I know, sometime I have problem naming vars :)))) –

1

Run code snippetExpand snippetFollowanswered Jan 20, 2022 at 17:253,53922 gold badges77 silver badges2121 bronze badges1

Merge objects with the same id but sum values of the objects
Ask Question
5 years, 7 months ago
javascript
group-by
reduce
Rep
Jun 2, 2017 at 21:13
Nenad Vracar
Jun 2, 2017 at 21:40
link
Rep
Jun 3, 2017 at 10:07
Add a comment
Array#reduce
How to sum the array of object values and assigned them to the relevant key name
How to sum the array of object values and assigned them to the relevant key name
Ask Question
3 months ago
javascript
arrays
object
filtering
dariusz
Jan 20, 2022 at 17:01
Gass
Jan 21, 2022 at 6:45
cmgchess
Jan 21, 2022 at 13:59
Add a comment
dariusz
Jan 20, 2022 at 17:18
Gass
Jan 20, 2022 at 19:20
Galterius
Jan 20, 2022 at 20:33
Add a comment
Share
Improve this question
edited Jun 2, 2017 at 15:19
Emile Bergeron
Rep
Add a comment
Share
Improve this answer
edited Jun 2, 2017 at 15:24
Emile Bergeron
Nenad Vracar
Share
Improve this question
dariusz
Add a comment
Share
Improve this answer
edited Sep 30, 2022 at 15:49
cmgchess
Share
Improve this answer
Galterius
Share
Improve this answer
jsN00b
Add a comment
dariusz's user avatar
Emile Bergeron's user avatar
Emile Bergeron's user avatar
Rep's user avatar
cmgchess's user avatar
Galterius's user avatar
jsN00b's user avatar
Nenad Vracar's user avatar