I need to add events to the existing date so i think i need to change my json structure something like below. I tried to achieve it via reduce as shown below
I want to convert this array of object
"sunday": [
"...",
7,
14,
21,
28
]
To
{
"sunday":[
{
"7":[
"event1",
"event2",
"event3"
]
},
{
"14":[
"event3",
"event4",
"event5"
]
},
{
"21":[]
},
{
"28":[]
}
]
}
Here is the data that has event's detail,
{
"data": [
{ "date": "7",
"events": ["event1", "event2", "event3"]
},
{ "date": "14",
"events": ["event3", "event4", "event5"]
},
]
}
What i tried and failed,
attachEventsToTheDate(week_days) {
var answer = [week_days].reduce(function(result, item, index) {
var key = Object.keys(item)[0];
var value = item[key][index];
var obj = {};
obj[key] = [obj[key]];
console.log('obj is', JSON.stringify(obj));
// JSON.stringify(obj);
// result.push(obj);
return result;
}, {}); //an empty array
}
map it:
var sunday = [ 7, 14, 21, 28 ]
var data = [ { "date": "7", "events": ["event1", "event2", "event3"] }, { "date": "14", "events": ["event3", "event4", "event5"] }]
console.log(sunday.map(x => {
var actual = data.find(y => y.date == x);
if(actual) {
return {[x]: actual.events}
} else {
return {[x]: []}
}
}))
.as-console-wrapper { max-height: 100% !important; top: 0; }
The object structure you desire to have will not be very efficient to work with, but here it is:
function groupEvents(week_days, events) {
const numToDay = []; // Extra index into the week_days nested objects
// Create a new week_days object
week_days = Object.assign(...Object.keys(week_days).map( day =>
({ [day]: week_days[day].filter(Number).map(num =>
({ [num]: numToDay[num] = [] })
)})
));
// Inject the events data into it
for (const data of events.data) {
// Skip if this day does not exist in the original week_days structure
if (!numToDay[data.date]) continue;
numToDay[data.date].push(...data.events);
}
return week_days;
}
const week_days = {sunday: ["...", 7, 14, 21, 28]},
events = {data: [
{ date: "7", events: ["event1", "event2", "event3"] },
{ date: "14", events: ["event4", "event5"] }
]};
const res = groupEvents(week_days, events);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
A more generic solution
The week_days object seems to be a translation of a certain month. If one has just the month, the week_days structure can be derived from it. So the key information is really your events object. If you can turn that object (as specified in your original question, i.e. with year and month info included) into something grouped by year-month combinations, and then produce for each combination a week_days kind of structure, you'll have all you need.
At the same time it seems more logical to use the day numbers as keys in the week_days nested objects.
Here is a demo on how you can do that:
const events = {
"data": [
{ "year": "2017", "month": "january", "date": "16",
"events": ["event1", "event2", "event3"]
},
{ "year": "2017", "month": "january", "date": "8",
"events": ["event4", "event5"]
},
]
};
function groupEvents(events) {
const dayNames = ['sunday', 'monday', 'tuesday', 'wednesday',
'thursday', 'friday', 'saturday'];
return events.data.reduce( (acc, o) => {
const key = o.month.toLowerCase() + " " + o.year;
if (!acc[key]) {
acc[key] = Object.assign(...dayNames.map(day => ({ [day]: {} })));
const dt = new Date("1 " + key);
const month = dt.getMonth();
while (dt.getMonth() === month) {
acc[key][dayNames[dt.getDay()]][dt.getDate()] = [];
dt.setDate(dt.getDate()+1);
}
}
const dt = new Date(o.date + " " + key);
acc[key][dayNames[dt.getDay()]][dt.getDate()].push(...o.events);
return acc;
}, {});
}
const res = groupEvents(events);
console.log(res);
.as-console-wrapper { max-height: 100% !important; top: 0; }
If now you want to have only the data of the month January 2017 (for example), you can just take it out of the result from the above script as follows:
const january2017_week_days = res["january 2017"];
Related
[
{
"timing": [
{
"zone": 18.8
},
{
"zone": 17.06,
},
{
"zone": 16.6
},
]
},
{
"timing": [
{
"zone": 12.6,
},
{
"zone": 14.6,
}
]
},
{
"timing": [
{
"zone":19.06,
},{
"zone": 8.06,
}
]
}
]
Here i am trying to work manipulate with one json data using javascript.
But, I am not able to think any approach how to achive that.
I am expecting below json. It give zone1, zone2, zone3 as per the zone any it will be dynamically
Please have a look to below json.
[
{
"zone1": [18.8, 12.6, 19.06 ]
},{
"zone2": [17.06, 14.6, 8.06]
}, {
"zone3":[16.6]
}
]
This is the output of json how it should look like.
Please have a look
You can use reduce and forEach
Loop through data, set OP's initial value as an object
Loop through timing property of each element, check if the zone + index + 1 exists in op or not, if exists push zone to that key else initialise new key
let data = [{"timing": [{"zone": 18.8},{"zone": 17.06,},{"zone": 16.6},]},{"timing": [{"zone": 12.6,},{"zone": 14.6,}]},{"timing": [{"zone": 19.06,}, {"zone": 8.06,}]}]
let final = data.reduce((op, { timing }) => {
timing.forEach(({ zone }, i) => {
let key = `zone${ 1 + i }`
op[key] = op[key] || []
op[key].push(zone)
})
return op
}, {})
console.log(final)
// If you need final output to be array of object just use entries and map to build a desired output
console.log(Object.entries(final).map(([k,v])=>({[k]:v})))
Here's a possible solution
var data = [{
"timing": [{
"zone": 18.8
},
{
"zone": 17.06,
},
{
"zone": 16.6
},
]
},
{
"timing": [{
"zone": 12.6,
},
{
"zone": 14.6,
}
]
},
{
"timing": [{
"zone": 19.06,
}, {
"zone": 8.06,
}]
}
];
// Calculate the total number of zones
var totalZones = 0;
for (let i = 0; i < data.length; i++) {
const currZones = data[i].timing.length;
if (currZones > totalZones) totalZones = currZones;
}
console.log(totalZones);
// Create the final Array
var result = new Array(totalZones);
for (let i = 0; i < totalZones; i++) {
result[i] = {
zone: []
}
}
// Populate the final array with values
for (let i = 0; i < totalZones; i++) {
for (let j = 0; j < data.length; j++) {
let currTiming = data[j].timing[i];
if (currTiming !== undefined) {
let currZone = data[j].timing[i].zone;
if (currZone !== undefined) {
result[i].zone.push(currZone);
}
}
}
}
console.log(result);
1) Gather all zone values into one array of array
2) Calculate max rows needed for zones
3) Have a simple for-loop till max rows and use shift and push methods.
const data = [
{
timing: [
{
zone: 18.8
},
{
zone: 17.06
},
{
zone: 16.6
}
]
},
{
timing: [
{
zone: 12.6
},
{
zone: 14.6
}
]
},
{
timing: [
{
zone: 19.06
},
{
zone: 8.06
}
]
}
];
const zones = data.map(time => time.timing.map(z => z.zone));
const rows = zones.reduce((rows, arr) => Math.max(rows, arr.length), 0);
const all = [];
for (let index = 1; index <= rows; index++) {
const res = [];
zones.forEach(zone => zone.length > 0 && res.push(zone.shift()));
all.push({ [`zone${index}`]: res });
}
console.log(all);
const input = [ {"timing": [{"zone": 18.8},{"zone": 17.06,},{"zone": 16.6},]},{"timing": [{"zone": 12.6,},{"zone": 14.6,}]},{"timing": [{"zone":19.06,},{"zone": 8.06,}]}]
var data = input.map(t => t.timing.map(u => u.zone));
var output = data[0].map((col, i) => data.map(row => row[i])).map((item, index) => {res = {}; res["zone"+(index+1)] = item.filter(t => t!==undefined); return res});
console.log(output);
Not the shortest, but it's very readable.
var json = [{"timing": [{"zone": 18.8},{"zone": 17.06,},{"zone": 16.6},]},{"timing": [{"zone": 12.6,},{"zone": 14.6,}]},{"timing": [{"zone": 19.06,}, {"zone": 8.06,}]}];
// index 0 is zone1, index 1 is zone2, index 2 is zone3, and so on ...
var zones = [];
// Loop through each 'timing' object
json.forEach(function(timingObject) {
var timing = timingObject['timing'];
// loop through each 'zone' in the given 'timing' object
timing.forEach(function(zoneObject, index) {
var zone = zoneObject['zone'];
// if the zone exists in the zones[] defined above
// add the current zone to its place
//
// if not (else), we have to add the array for the
// current index, then add the value of the current zone.
if(zones[index]) {
zones[index]['zone' + (index + 1)].push(zone);
} else {
zones.push({ ['zone' + (index + 1)]: [zone]})
}
});
});
console.log(zones);
I need some help. I need to calculate the amount of user actions in each month of current year. I have an array of dates:
let years = ['2017', '2018', '2019']
let datesArray = [
{date: "2019-06-05", userActionsAmount: 88},
{date: "2019-06-04", userActionsAmount: 314}
]
and I have the count object
let counts = {}
then I iterate through this like that:
years.forEach(year => {
counts[year] = datesArray.filter(singleDay => singleDay.date.slice(0, -6) === year).reduce((acc, obj) => {
return acc + obj.userActionsAmount
}, 0)
})
with this code result of counts is:
{2017: 0, 2018: 0, 2019: 402} which is ok, but I need to break the date in to months, so I need something like this:
{ 2017: []},
{ 2018: []}
{ 2019: [
{ '01': 0 },
{ '02': 0 },
{ '03': 0 },
{ '04': 0 },
{ '05': 0 },
{ '06': 402 },
{ '07': 0 },
{ '08': 0 },
{ '09': 0 },
{ '10': 0 },
{ '11': 0 },
{ '12': 0 }
]}
you can do it like this:
let datesArray = [
{date: "2019-06-05", userActionsAmount: 88},
{date: "2019-06-04", userActionsAmount: 314}
]
let result={};
datesArray.forEach(dateItem=>{
let date=dateItem.date.split("-");
let year=date[0];
let month=date[1];
if(!result[year])
result[year]={};
if(!result[year][month])
result[year][month]=0;
result[year][month]+=dateItem.userActionsAmount;
})
That's basically a very simple grouping
const datesArray = [
{date: "2019-06-05", userActionsAmount: 88},
{date: "2019-06-04", userActionsAmount: 314}
];
const groupedByMonth = datesArray.reduce((a, b) => a.set(b.date.substring(0,7), ~~a.get(b.date.substring(0,7)) + b.userActionsAmount), new Map);
console.log([...groupedByMonth]);
To get it to your format, you could do something like
const yourFormat = years.map(e => ({
[e]: Array.from(groupedByMonth).filter(([k, v]) => k.substring(0,4) === e).map(([k, v]) => ({[k.substring(5,7)]: v}))
}));
then
You could create properties when needed.
Here are two solutions : one with array methods and second more explicit.
Initialization :
const monthsKeys = ["01", "02", "03","04", "05", "06", "07", "08", "09", "10", "11", "12"];
const years = ['2017', '2018', '2019'];
const datesArray = [
{date: "2019-06-05", userActionsAmount: 88},
{date: "2019-06-04", userActionsAmount: 314}
];
const counts = {};
Solution 1 :
years.forEach( y => { counts[y] = []; });
datesArray.forEach(dateCount => {
const [year, month, day] = dateCount.date.split("-");
if (counts[year].length === 0) monthsKeys.forEach(m => {counts[year].push({[m] : 0});});
counts[year][Number(month) - 1][month] += dateCount.userActionsAmount;
});
console.log(counts);
Solution 2 :
// fill counts with years
for (const y of years) {
counts[y] = [];
}
// fill counts with months and count
for (const e of datesArray) {
const splittedDate = e.date.split("-");
const year = splittedDate[0];
const month = splittedDate[1];
// create year if needed, not necessary if years array is sure
if ( ! year in counts) {
counts[year] = [];
}
// create monthes if needed
if (counts[year].length === 0) {
for (const m of monthsKeys) {
counts[year].push({[m]: 0});
}
}
// add value
counts[year][Number(month) - 1][month] += e.userActionsAmount;
}
console.log(counts)
Why an array of objects for year values (months counts) and not simply an object?
This solution has some varation from the OP's expected output, but I believe that it should fit OP's requirements. If not, it's about a step to get the output as desired...
const years = [2017, 2018, 2019]
const dates = [{
date: "2019-06-05",
userActionAmount: 88
},
{
date: "2019-06-04",
userActionAmount: 314
}
]
const transform = (years, dates) => dates.reduce(
(output, {
date,
userActionAmount,
parsedDate = new Date(date),
year = parsedDate.getFullYear(),
month = parsedDate.getMonth() + 1,
yearData = output[year]
}) =>
(yearData[month] += userActionAmount) && output,
Object.fromEntries(years.map(year => [year, Object.fromEntries(Array.from({
length: 12
}, (_, x) => [x + 1, 0]))])))
const output = transform(years, dates)
console.log(output)
// This output lets you get total amount
// of some given month in the following way:
const monthAmount = output[2019][6]
console.log (monthAmount)
I have an array as below
array1 = [{"month":"January","location":"CENTRAL","percentage":94},
{"month":"February","location":"CENTRAL","percentage":97},
{"month":"March","location":"CENTRAL","percentage":93},
{"month":"January","location":"NORTH","percentage":95},
{"month":"February","location":"NORTH","percentage":91},
{"month":"March","location":"NORTH","percentage":98}];
I want to format my array to look as below
array2= [{
location: "CENTRAL",
January: 94,
February: 97,
March: 93},
{
location: "NORTH",
January: 95,
February: 91,
March: 98}];
I tried to use group by function as below
function groupBy(list, keyGetter) {
const map = new Map();
list.forEach((item) => {
const key = keyGetter(item);
if (!map.has(key)) {
map.set(key, [item]);
} else {
map.get(key).push(item);
}
});
return map;
}
const grouped = groupBy(array1, arr => arr.location);
console.log(grouped);
but I am not getting the same format. Any suggestions please what I am missing in my idea ? Thank you very much.
You can indeed use a map keyed by location, but then with plain objects as values. The problem in your code is that you push items into an array, and don't turn the month values into properties of a singular object (per location).
So given a map with plain objects, iterate the input and inject the month properties into those plain objects, with corresponding percentage values, and then take the values of that map:
const array1 = [{"month":"January","location":"CENTRAL","percentage":94},{"month":"February","location":"CENTRAL","percentage":97},{"month":"March","location":"CENTRAL","percentage":93},{"month":"January","location":"NORTH","percentage":95},{"month":"February","location":"NORTH","percentage":91},{"month":"March","location":"NORTH","percentage":98}];
const map = new Map(array1.map(({location}) => [location, { location }]));
array1.forEach(o => map.get(o.location)[o.month] = o.percentage);
const result = [...map.values()];
console.log(result);
You could use a dynamic approach by handing over the group key, the keys for key and value for collecting.
Then add all key/value pairs to the object and later return the values of the map.
function groupBy(list, group, key, value) {
return Array.from(list
.reduce((map, object) => map.set(object[group], Object.assign(
map.get(object[group]) || { [group]: object[group] },
{ [object[key]]: object[value] }
)), new Map)
.values()
);
}
var array = [{ month: "January", location: "CENTRAL", percentage: 94 }, { month: "February", location: "CENTRAL", percentage: 97 }, { month: "March", location: "CENTRAL", percentage: 93 }, { month: "January", location: "NORTH", percentage: 95 }, { month: "February", location: "NORTH", percentage: 91 }, { month: "March", location: "NORTH", percentage: 98 }],
result = groupBy(array, 'location', 'month', 'percentage');
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
An alternative is using the function reduce to group by location and the function Object.values to extract the grouped objects.
let array1 = [{"month":"January","location":"CENTRAL","percentage":94},{"month":"February","location":"CENTRAL","percentage":97},{"month":"March","location":"CENTRAL","percentage":93},{"month":"January","location":"NORTH","percentage":95},{"month":"February","location":"NORTH","percentage":91},{"month":"March","location":"NORTH","percentage":98}],
groupBy = (array, keygetter) => {
return Object.values(array1.reduce((a, {month, percentage, ...rest}) => {
let key = keygetter(rest);
(a[key] || (a[key] = {location: key}))[month] = percentage;
return a;
}, Object.create(null)));
},
result = groupBy(array1, (o) => o.location);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
One approach is to use .filter() and .map()
var array1 = [{"month":"January","location":"CENTRAL","percentage":94},
{"month":"February","location":"CENTRAL","percentage":97},
{"month":"March","location":"CENTRAL","percentage":93},
{"month":"January","location":"NORTH","percentage":95},
{"month":"February","location":"NORTH","percentage":91},
{"month":"March","location":"NORTH","percentage":98}];
const groupBy = (arr, prop, propName1, propName2, propName3) =>
Object.assign({[prop]:propName1}
, ...arr.filter(({[prop]:p}) => p === propName1)
.map(({[propName2]:m, [propName3]:p}) => ({[m]: p}))
);
const locations = ["CENTRAL", "NORTH"];
let res = locations.map(prop => groupBy(array1, "location", prop, "month", "percentage"));
console.log(res);
The problem is, you can't just rearrange the properties in an object. According to the ECMAScript specifications:
An ECMAScript object is an unordered collection of properties
You can rearrange the properties using your function, but the order will not be guaranteed in the final object.
Here is another example using reduce, pass the callback function and specify the key in it
array1 = [{
"month": "January",
"location": "CENTRAL",
"percentage": 94
},
{
"month": "February",
"location": "CENTRAL",
"percentage": 97
},
{
"month": "March",
"location": "CENTRAL",
"percentage": 93
},
{
"month": "January",
"location": "NORTH",
"percentage": 95
},
{
"month": "February",
"location": "NORTH",
"percentage": 91
},
{
"month": "March",
"location": "NORTH",
"percentage": 98
}
];
function groupBy(list, callback) {
return list.reduce((acc, x) => {
const key = callback(x);
if (!acc[key]) {
return {
...acc,
[key]: [x]
}
}
return {
...acc,
[key]: [...acc[key], x]
}
}, {})
}
// callback function
function locationName(obj) {
return obj.location
}
console.log('group by location name:', groupBy(array1, locationName));
{
"rResponse":{
"rDetailsList":[
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
]
}
}
getFilteredResult(rDetails, searchText) {
const regex = new RegExp(searchText, 'i');
let result= rDetails.filter(a =>
a.rList.some(rItem=>
(rItem.aName.search(regex) > -1) ||
(rItem.aNumber.search(regex) > -1)
))
console.log(result,"filteredResults")
return result;
}
let result=getFilteredResult(rResponse.rDetailsList, "A270M040558"):
I am using the above function for filtering the data based on search string.
I want to filter the nested array of object keep the structure of the object same
The output of the above function is below, where i am getting all object of a list instead of getting only one object which matches the search text
{
"rResponse": {
"rDetailsList": [{
"rDate": "Jan 01, 2018",
"rList": [{
"aName": "",
"aNumber": "A39A4035073"
},
{
"aName": "YVTLW K SIGLC",
"aNumber": "A270M040558"
}
]
}]
}
}
The expected Output is
{
"rResponse": {
"rDetailsList": [{
"rDate": "Jan 01, 2018",
"rList": [
{
"aName": "YVTLW K SIGLC",
"aNumber": "A270M040558"
}
]
}]
}
}
You have 2 arrays, so you need to filter the first one then the second one :
const rDetailsList = [
{
"rDate":"April 01, 2018",
"rList":[
{
"aName":"GOKQG C HQFUDHFPX",
"aNumber":"P3799838628"
},
{
"aName":"IGNDPJR D EKYJYC",
"aNumber":"P3899820579"
}
]
},
{
"rDate":"Jan 01, 2018",
"rList":[
{
"aName":"",
"aNumber":"A39A4035073"
},
{
"aName":"YVTLW K SIGLC",
"aNumber":"A270M040558"
}
]
}
];
const myFilter = (arr, num) => {
const rDetails = arr.filter(det => !!det.rList.find(l => l.aNumber === num));
return rDetails.map(det => {
det.rList = det.rList.filter(l => l.aNumber === num);
return det;
});
};
console.log(myFilter(rDetailsList, 'A270M040558'));
const res = _.chain(rDetailsList)
.map(rDetail => _.assign( // iterate array and set filtered rList
{}, // use new object to avoid mutations
rDetail,
{ rList: _.filter(rDetail.rList, { aNumber: 'A270M040558' }) }
))
.reject(rDetail => _.isEmpty(rDetail.rList)) // remove elements with empty rList
.value();
I have a json file with multiple transactions with a date and a price attribute. Now I want to compare the dates and if they are in the same month and year I want to sum up the prices.
JSON:
transactions: [
{
date: "2017-11-17",
price: "28",
},
{
...
}
JavaScript:
request.onload = function() {
for(const transaction of request.response.transactions) {
let year = new Date(transaction.date).getFullYear();
let month = new Date(transaction.date).getMonth();
console.log(year + ' ' + month); // output: 2017-11 ...
}
};
I tried to loop over the json object but I struggle to find a solution to compare the dates.
Edit: Edited example with Object.assign instead of Object spread.
You'll need to use reduce to sum the prices. See comments for details.
const transactions = [{
date: "2017-11-17",
price: "28",
},
{
date: "2017-12-17",
price: "23",
},
{
date: "2017-11-17",
price: "12",
},
{
date: "2017-10-17",
price: "55",
},
{
date: "2017-11-17",
price: "09",
},
];
const sumTransactions = (transactions) => {
const summed = transactions.reduce((acc, current) => {
// Get the current date object
const date = new Date(current.date);
// Create your key/identifier
const key = `${date.getFullYear()}-${date.getMonth() + 1}`;
// Retreive the previous price from the accumulator
const previousPrice = acc[key]; // Might also return undefined
// Create your temp current price value, and be sure to deal with numbers.
let currentPrice = Number(current.price);
// If you had a previous value (and not undefined)
if (previousPrice) {
// Add it to our value
currentPrice += Number(previousPrice);
}
// Return the future accumulator value
return Object.assign(acc, {
[key]: currentPrice, // new values will overwrite same old values
})
}, {})
// Once we have all values, get the dates, and sort them (default: earlier first)
// Return an array of each value from the summed object to our sortedArray
const sortedArray = Object.keys(summed).sort().map((val) => {
return summed[val];
});
console.log("sortedArray", sortedArray);
};
sumTransactions(transactions);
I experimented a bit and came up with this solution:
var transactions = [
{
date: "2017-11-17",
price: "28",
},
{
date: "2017-12-17",
price: "22",
},
{
date: "2017-12-17",
price: "20",
}
]
var sumedUpDates = [];
var prices = [];
function isDateSumedUp(date) {
return sumedUpDates.indexOf(date.substring(0, 7)) !== -1;
}
function sumUpDate(date) {
var sum = 0;
transactions.forEach(t => {
if(t.date.substring(0, 7) === date.substring(0, 7)) {
sum += parseInt(t.price);
}
});
sumedUpDates.push(date.substring(0, 7));
prices.push(sum);
}
transactions.forEach(t => {
if(!isDateSumedUp(t.date)) {
sumUpDate(t.date);
}
});
var obj = {};
sumedUpDates.forEach((d, i) => obj[d] = prices[i]);
console.log(obj);
This solutions uses map to format your dates into year/month format for each object entry and then reduce to sum them by those separated dates.
const transactions = [
{date:"2017-11-17", price: "28",},
{date:"2017-12-17", price: "28",},
{date:"2017-11-17", price: "20",},
{date:"2017-12-17", price: "2",},
{date:"2017-11-17", price: "58",},
{date:"2017-11-17", price: "8",},
{date:"2017-10-17", price: "30",},
{date:"2018-11-17", price: "1",},
];
const mapper = single => {
let d = single.date.split('-');
let p = Number(single.price);
return { year: d[0], month: d[1], price: p };
}
const reducer = (group, current) => {
let i = group.findIndex(single => (single.year == current.year && single.month == current.month));
if (i == -1) {
return [ ...group, current ];
}
group[i].price += current.price;
return group;
};
const sumPrices = transactions.map(mapper).reduce(reducer, []);
console.log(sumPrices);
var array = [];
for (var i = 0; i < transactions.length; i++) {
var date = new Date(transactions[i].date);
var ym = date.getFullYear() + "-" + date.getMonth();
if (array[ym] == null) {
array[ym] = 0;
}
array[ym] += parseInt(transactions[i].price);
}
With this data
var transactions = [{
date: "2017-11-17",
price: "28",
},
{
date: "2017-12-17",
price: "5",
},
{
date: "2016-02-17",
price: "28",
},
{
date: "2015-11-17",
price: "25",
},
{
date: "2016-02-17",
price: "12",
},
{
date: "2017-11-17",
price: "50",
}
];
This will give you the sum of all of the year-months duplicates like this :
[
2017-10: 78,
2017-11: 5,
2016-1: 40,
2015-10: 25
]
Another solution is reduce:
var transactions = [
{date: "2017-11-17",price: "28"},
{date: "2017-12-17",price: "22"},
{date: "2017-12-17",price: "20"}
];
var result = transactions.reduce(function(acc, obj) {
var key = obj.date.substr(0,7);
acc[key] = (acc[key] || 0) + +obj.price;
return acc;
}, Object.create(null));
console.log(result);