javascript - Pushing non existent items to array -


so have array:

var period = [{"total":852, "date":"2016-03"}, {"total":963, "date":"2016-03"},{"total":789,"date":"2016-02"},{"total":456,"date":"2016-04"},{"total":123,"date":"2016-01"},{"total":723,"date":"2016-01"}]; 

i need display "total" data grouped month. means have sum "total" amount on months repeated on array (2016-03, 2016-01). find solution need understand why this

for ( var = 0; < period.length; i++ ){  if (periodb.indexof(period[i].date) == -1){      periodb.push(period[i].date);    } 

returns this:

  ["2016-03", "2016-02", "2016-04", "2016-01"] 

while this:

for ( var = 0; < period.length; i++ ){   if (periodb.indexof(period[i].date) == -1){   periodb.push({"date": period[i].date, "total": period[i].total});   } } 

is returning this:

  [{date: "2016-03",total: 1704}, {date: "2016-03", total: 1926}, {date:"2016-02", total: 1578},{date: "2016-04",total: 912}, {date: "2016-01",total: 246}, {date: "2016-01", total: 1446 }] 

on first case repeated "dates" not being pushed on periodb array, on second case are.

you can solve task using temporary object , 1 foreach loop

var obj = {};  period.foreach(e => {     var month = e.date.split('-')[1]     obj[month] = obj[month] + e.total || e.total }); 

result object month key , total sum value

{     '03': 1815,      '02': 789,     '04': 456,     '01': 846 } 

working example:

var period = [{ "total": 852, "date": "2016-03" }, { "total": 963, "date": "2016-03" }, { "total": 789, "date": "2016-02" }, { "total": 456, "date": "2016-04" }, { "total": 123, "date": "2016-01" }, { "total": 723, "date": "2016-01" }];    var obj = {};    period.foreach(e => {      var month = e.date.split('-')[1]      obj[month] = obj[month] + e.total || e.total  });    document.write(json.stringify(obj, 0, 2));


Comments

Popular posts from this blog

java - nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet Hibernate+SpringMVC -

sql - Postgresql tables exists, but getting "relation does not exist" when querying -

asp.net mvc - breakpoint on javascript in CSHTML? -