I have this array of object:
let attend = [
{
style: 'Big',
date: '03/01/2016'
},
{
style: 'Big',
date: '03/01/2016'
},
{
style: 'Small',
date: '04/01/2016'
},
{
style: 'Small',
date: '03/01/2016'
},
{
style: 'Big',
date: '01/01/2016'
}
]
and this array: let now = ['01/01/2016', '02/01/2016', '03/01/2016']
which I’d like to use in comparing, counting, and formating the array of object BASED on the date, in summary, I’d want the result to look like this:
{
name: 'Big',
data: [1, 0, 2]
},
{
name: 'Small',
data: [0, 0, 2]
}
Any suggestion would be appreciated, thanks a lot
This is how i did in the shortest possible time and it’s not the most efficient solution but does the job.
let attend = [
{
style: 'Big',
date: '03/01/2016'
},
{
style: 'Big',
date: '03/01/2016'
},
{
style: 'Small',
date: '04/01/2016'
},
{
style: 'Small',
date: '03/01/2016'
},
{
style: 'Big',
date: '01/01/2016'
}
];
let now = ['01/01/2016', '02/01/2016', '03/01/2016'];
let intitalValueArr = [];
let middlewareObj = {};
//inserting 0 in the array for intialization in the code
now.forEach(element => {
intitalValueArr.push(0);
});
//manipulating and storing the data for easy formatting
for (let i = 0; i < now.length; i++) {
attend.forEach(element => {
if (element.date === now[i]) {
//checking if the style already exist in the middleware object
if (middlewareObj.hasOwnProperty(element.style)) {
middlewareObj[element.style][i]++;
} else {
middlewareObj[element.style] = [...intitalValueArr];
middlewareObj[element.style][i]++;
}
}
});
}
//now formatting the unformatted middlewareObj
let formattedArr = [];
Object.keys(middlewareObj).forEach(element => {
let insertObj = {};
insertObj[element] = middlewareObj[element];
formattedArr.push(insertObj);
});
console.log(formattedArr);
Oh kashimi, you are a lifesaver. Thank you very very MUCH, I really appreciate it!