I am literally a newbie to javascript, I have this kind of data series
[3,3,4,5,5,6]
in the form of array I want to arrange it, what I expect as output is
(2 of 3) (1 of 4) (2 of 5) (1 of 6)
Can someone please help me solve this issue?
I need to display this data in a chart, I am using chartJS, the number is in the form of months (1 is January 2 is February....)
this ho really my data looks like
021-06-20T16:17:35.000000Z
2021-07-19T00:17:35.000000Z
2021-07-20T00:17:35.000000Z
2021-07-21T00:17:35.000000Z
2021-07-21T00:17:35.000000Z
2021-08-21T00:17:35.000000Z
What I really expect is to have a array of object in this form
[{data : '06',count : 1},
{data : '07',count : 4},
{data : '08',count : 1}]
Is there any trick I can do it with chartjs without formating my data?
You can do this many ways altho I'm just gonna give you one.
function callback(acc, child) {
let isCreated = acc.find((ch) => ch.data === child);
if (isCreated) {
isCreated.count++;
} else {
acc.push({ data: child, count: 1 });
}
return acc;
}
let data = [3, 3, 4, 5, 5, 6].reduce(callback, []);
console.log(data);
log should be
[
{ data: 3, count: 2 },
{ data: 4, count: 1 },
{ data: 5, count: 2 },
{ data: 6, count: 1 }
]
You can simply use this, might help:
// This is the test array
var a = [1,1,1,2,2,3,4,4,5];
// This will create object below
// { 1: 3, 2: 2, 3: 1, 4: 2, 5: 1}
var counter = a.reduce((state,current)=> (state[current] = (state[current] || 0) + 1, state),{});
// This will log the output you mentioned
for (const [number, count] of Object.entries(counter)) {
console.log(`(${count} of ${number})`);
}
Solution:
a = [3,3,4,5,5,6]
new Set(a).forEach(x => console.log('data: ' + x + ', count: ' + a.filter(y => y === x).length));
Output:
data: 3, count: 2
data: 4, count: 1
data: 5, count: 2
data: 6, count: 1