How to match key from 1 array to another object and get sum of every key

javascript sum object values by key
javascript sum array of objects
javascript array group by sum
javascript reduce
javascript sum array of objects reduce
reduce array to object
jquery sum array of objects
javascript reduce array of objects by key

I have 1 object with complete data, and 2 array of keys those are exist in object, how can i get sum of every key of from 2 array.

const data = [{
  DateMeasured: "8/30/2018",
  AsthmaDiaryReading: "100",
  AsthmaDiaryPersonalBest: "100",
  Comment: ""
},{
  DateMeasured: "8/29/2018",
  AsthmaDiaryReading: "200",
  AsthmaDiaryPersonalBest: "150",
  Comment: ""
},{
  DateMeasured: "8/15/2018",
  AsthmaDiaryReading: "300",
  AsthmaDiaryPersonalBest: "50",
  Comment: ""
},{
  DateMeasured: "8/6/2018",
  AsthmaDiaryReading: "100",
  AsthmaDiaryPersonalBest: "200",
  Comment: ""
},{
  DateMeasured: "9/6/2017",
  AsthmaDiaryReading: "500",
  AsthmaDiaryPersonalBest: "100",
  Comment: ""
}
];

Sum key,

array = [
      'AsthmaDiaryReading',
      'AsthmaDiaryPersonalBest'
    ]

Desire sum should be like below:

object = {
  AsthmaDiaryReading: "1200" ,
  AsthmaDiaryPersonalBest: '600'
}

You can use of Array.reduce()

const data = [{
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '100',
  },
  {
    AsthmaDiaryReading: '200',
    AsthmaDiaryPersonalBest: '150',
  },
  {
    AsthmaDiaryReading: '300',
    AsthmaDiaryPersonalBest: '50',
  },
  {
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '200',
  },
  {
    AsthmaDiaryReading: '500',
    AsthmaDiaryPersonalBest: '100',
  },
];

dataKeys = [
  'AsthmaDiaryReading',
  'AsthmaDiaryPersonalBest'
];

const initialArray = dataKeys.reduce((tmp, x) => ({
  ...tmp,

  [x]: 0,
}), {});

const ret = data.reduce((tmp, x) => {
  Object.keys(tmp).forEach((y) => {
    tmp[y] += parseInt(x[y]);
  });

  return tmp;
}, initialArray);

console.log(ret);

array_intersect_key - Manual, array_intersect_key — Computes the intersection of arrays using keys for array_intersect_key() returns an array containing all the entries of array1 which have keys that are present in all A match still occurs because only the keys are checked. In other words a strict type check is executed so the string representation  Array; Plain objects also support similar methods, but the syntax is a bit different. Object.keys, values, entries. For plain objects, the following methods are available: Object.keys(obj) – returns an array of keys. Object.values(obj) – returns an array of values. Object.entries(obj) – returns an array of [key, value] pairs.

Using reduce with a for in loop inside is shorter:

const data = [{
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '100',
  },
  {
    AsthmaDiaryReading: '200',
    AsthmaDiaryPersonalBest: '150',
  },
  {
    AsthmaDiaryReading: '300',
    AsthmaDiaryPersonalBest: '50',
  },
  {
    AsthmaDiaryReading: '100',
    AsthmaDiaryPersonalBest: '200',
  },
  {
    AsthmaDiaryReading: '500',
    AsthmaDiaryPersonalBest: '100',
  },
];

var res = data.reduce((acc,c)=>{
    for(let a in c){
        acc[a] = (acc[a] || 0)+parseInt(c[a]);
    }    
    return acc;
},{})//<-- associative array if you change {} for []

console.log(Object.keys(res))

console.log(res)

Array methods, The arrays are objects, so we can try to use delete : let arr = [ "I" , "go" That's natural, because delete obj.key removes a value by the key . It's all it The function is called for elements of the array, one after another: item is the The syntax is similar to find , but filter returns an array of all matching elements:. The keys () method returns a new Array Iterator object that contains the keys for each index in the array. JavaScript Demo: Array.keys () var array1 = ['a', 'b', 'c']; var iterator = array1.keys (); for (let key of iterator) { console.log (key); // expected output: 0 1 2 } JavaScript Demo: Array.keys () The source for this interactive example

A pure reduce option, albeit not very pretty:

const sumOfKeys = (keys, data) => data.reduce(
  (total, entry) =>
    keys.reduce(
      (acc, k) => ({ ...acc, [k]: (total[k] || 0) + Number(entry[k]) }),
      {},
    ),
  {},
);

sumOfKeys(dataKeys, data)

How to simplify your codebase with map(), reduce(), and filter() in , Well, this is the only one not about map/reduce/filter, but it's so compact that it was The filter() method creates a new array with all elements that pass the test Create an object that contains the frequency of the specified key JSON.​stringify can make the string output more readable, but not as a table: Object.keys and Array.map is all good old EcmaScript 5.1. (Yes the arrow function @isvforall used is ES6 but not really an interesting part of the answer, e.g see the answer by @rob-brander) – Emil Oberg Apr 4 '16 at 20:08

Visual Basic 2005 Programmer's Reference, The DataTable's XML properties affect the way the object reads and writes its data in XML Accepts all changes to the table's rows that were made since the data was Compute (“SUM(Score)”, “StudentId = 1”) calculates the total of the It searches the table for a row with values that match the array's primary key values. When there are multiple values for the same key in one of the inputs, the resulting pair RDD will have an entry for every possible pair of values with that key from the two input RDDs. A simple way to understand this is by looking at Example 4-17 .

PHP Array Functions, array_change_key_case(), Changes all keys in an array to lowercase or uppercase an array by using the elements from one "keys" array and one "​values" array array_diff_key(), Compare arrays, and returns the differences (​compare keys only) array_sum(), Returns the sum of the values in an array Get Certified »  Here is a generic solution that you can add to your Array library. All you need to do is supply the associated value and the target array! PHP Manual: array_search() (similiar to .indexOf() in other languages)

3.1. Design Documents, keys – Array of pairs of key-docid for related map function results. main task of reduce functions is to reduce the mapped result, not to make it bigger. group=​true will simply return a value of 1 for every distinct key in the view. A map function that emits an object containing sum , min , max , count , and sumsqr keys and  The every () method executes the function once for each element present in the array: If it finds an array element where the function returns a false value, every () returns false (and does not check the remaining values) If no false occur, every () returns true. Note: every () does not execute the function for array elements without values.

Comments
  • Please format your question for better code format. Enclose your code in `` for better formatting or check meta.stackexchange.com/questions/22186/…