Group array of dates and format to schedule - arrays

I need to group an array of dates and then format the group of dates into a schedule format.
Possible labels could be:
Weekdays (from Mon to Fri)
Weekends (Sat and Sun)
Monday-Tuesday (range of days with same schedule)
Wednesday (specific day with unique schedule)
Thursday, Saturday (specific group of days with same schedule)
For example:
Input Data
[
{
day: "monday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "tuesday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "wednesday",
start_time: "09:00",
end_time: "18:00"
},
{
id: 25,
day: "thursday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "friday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "saturday",
start_time: "10:00",
end_time: "17:00"
},
{
day: "sunday",
start_time: "10:00",
end_time: "17:00"
}
]
Expected Output
[
{
label: 'All weekdays', // Mon-Fri
value: '09:00 - 18:00',
},
{
label: 'Weekend', // Sat-Sun
value: '10:00 - 17:00',
},
];
And the output can be as follows, if start_time and end_time are different for each day
[
{
label: 'Monday', // one day
value: '09:00 - 20:00',
},
{
label: 'Tuesday, Thursday', // specific days with same schedule
value: '10:00 - 19:00',
},
{
label: 'Wednesday', // one day
value: '12:00 - 20:00',
},
{
label: 'Friday - Sunday', // range of days with same schedule
value: '10:00 - 17:00',
},
];
CodeSandbox with template - link

An approach for solving the OP's problem breaks down into ...
grouping/collecting all items (or day names) of a specific time-schedule/range
and creating the final result upon this first grouped and aggregated data,
... which one straightforwardly can implement by a reduce and a mapping task that would be accompanied by some helper functions which for example would ...
normalize any weekday's name
compare weekdays by their names
acquire the correct label of a time-schedule by e.g. an ordered list of unique weekday names.
The reduce task is going to create an object where each key already represent the final result's value, a string which represents a time range like e.g. '09:00 - 18:00' and where each of such a key's value is an array of each of the processed item's day-values (the latter being a string which represents a weekday's name with neither specific nor reliable latter-casing like e.g. 'monday' or 'Monday').
The map task would process the entries of such an above described object. Each entry's time-schedule related key gets assigned as the final items's value property. And each entry's weekday related value (an array of weekday names) is the base of computing the final item's label property.
Implementation ...
// helpers.
function normalizeNameOfWeekday(value) {
return value
.toLowerCase()
.replace(/^(\p{L})(.*)$/u, (_, first, last) =>
[first.toUpperCase(), last].join('')
);
}
function compareWeekdaysByName(a, b) {
const lookup = {
monday: 0, tuesday: 1, wednesday: 2,
thursday: 3, friday: 4,
saturday: 5, sunday: 6,
};
return lookup[a.toLowerCase()] - lookup[b.toLowerCase()];
}
function getTimeScheduleLabel(days) {
const lookup = {
monday_tuesday: 'Monday & Tuesday',
monday_tuesday_wednesday: 'Monday - Wednesday',
monday_tuesday_wednesday_thursday: 'Monday - Thursday',
monday_tuesday_wednesday_thursday_friday: 'All working days',
monday_tuesday_wednesday_thursday_friday_saturday: 'Monday - Saturday',
monday_tuesday_wednesday_thursday_friday_saturday_sunday: 'Every day of the week',
tuesday_wednesday: 'Tuesday & Wednesday',
tuesday_wednesday_thursday: 'Tuesday - Thursday',
tuesday_wednesday_thursday_friday: 'Tuesday - Friday',
tuesday_wednesday_thursday_friday_saturday: 'Tuesday - Saturday',
tuesday_wednesday_thursday_friday_saturday_sunday: 'Tuesday - Sunday',
wednesday_thursday: 'Wednesday & Thursday',
wednesday_thursday_friday: 'Wednesday - Friday',
wednesday_thursday_friday_saturday: 'Wednesday - Saturday',
wednesday_thursday_friday_saturday_sunday: 'Wednesday - Sunday',
thursday_friday: 'Thursday & Friday',
thursday_friday_saturday: 'Thursday - Saturday',
thursday_friday_saturday_sunday: 'Thursday - Sunday',
friday_saturday: 'Friday & Saturday',
friday_saturday_sunday: 'Friday - Sunday',
saturday_sunday: 'All weekend',
};
const scheduleFingerprint = [
// set of unique day-names.
...new Set(days)
]
// ordered list (of unique day-names).
.sort(compareWeekdaysByName)
// comparable schedule-fingerprint.
.join('_').toLowerCase();
return lookup[scheduleFingerprint] ?? days.map(normalizeNameOfWeekday).join(', ');
}
// reducer.
function collectDayOfSameTimeSchedule(index, { day, start_time, end_time }) {
const scheduleKey = `${ start_time } - ${ end_time }`;
// create and/or access the array of
// day-names of the same time-schedule
// and push another matching name into it.
(index[scheduleKey] ??= []).push(day);
return index;
}
// mapper.
function createTimeScheduleFromEntry([scheduleKey, listOfSameTimeScheduleDays]) {
return {
label: getTimeScheduleLabel(listOfSameTimeScheduleDays),
value: scheduleKey,
}
}
const sampleData_01 = [{
day: "monday", start_time: "09:00", end_time: "18:00",
}, {
day: "tuesday", start_time: "09:00", end_time: "18:00",
}, {
day: "wednesday", start_time: "09:00", end_time: "18:00",
}, {
id: 25, day: "thursday", start_time: "09:00", end_time: "18:00",
}, {
day: "friday", start_time: "09:00", end_time: "18:00",
}, {
day: "saturday", start_time: "10:00", end_time: "17:00",
}, {
day: "sunday", start_time: "10:00", end_time: "17:00",
}];
const sampleData_02 = [{
day: "monday", start_time: "09:00", end_time: "20:00",
}, {
day: "tuesday", start_time: "10:00", end_time: "19:00",
}, {
day: "wednesday", start_time: "12:00", end_time: "20:00",
}, {
id: 25, day: "thursday", start_time: "10:00", end_time: "19:00",
}, {
day: "friday", start_time: "10:00", end_time: "17:00",
}, {
day: "saturday", start_time: "10:00", end_time: "17:00",
}, {
day: "sunday", start_time: "10:00", end_time: "17:00",
}];
console.log(
'sample-data with 2 time-schedules ...',
Object
.entries(
sampleData_01
.reduce(collectDayOfSameTimeSchedule, {})
)
.map(createTimeScheduleFromEntry)
);
console.log(
'sample-data with 4 time-schedules ...',
Object
.entries(
sampleData_02
.reduce(collectDayOfSameTimeSchedule, {})
)
.map(createTimeScheduleFromEntry)
);
console.log('\n');
console.log(
'intermediate reducer-step of ... sample-data with 2 time-schedules ...',
sampleData_01
.reduce(collectDayOfSameTimeSchedule, {})
);
console.log(
'intermediate reducer-step of ... sample-data with 4 time-schedules ...',
sampleData_02
.reduce(collectDayOfSameTimeSchedule, {})
);
.as-console-wrapper { min-height: 100%!important; top: 0; }

I have written a snippet, it might help
var scheduleInfo = [
{
day: "monday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "tuesday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "wednesday",
start_time: "09:00",
end_time: "18:00"
},
{
id: 25,
day: "thursday",
start_time: "08:00",
end_time: "18:00"
},
{
day: "friday",
start_time: "09:00",
end_time: "18:00"
},
{
day: "saturday",
start_time: "10:00",
end_time: "17:00"
},
{
day: "sunday",
start_time: "10:00",
end_time: "17:00"
}
]
var tempOutput = [];
var output = [];
let allDays = ["monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday"]
var weekdays = ["monday", "tuesday", "wednesday", "thursday", "friday"]
weekdays = weekdays.sort();
//sort according to schedule
for (let i in scheduleInfo) {
let sch = scheduleInfo[i];
if (!allValue.includes(sch.start_time + sch.end_time)) {
allValue.push(sch.start_time + sch.end_time);
tempOutput.push({
label: sch.day,
start_time: sch.start_time,
end_time: sch.end_time
})
} else {
for (let j in tempOutput) {
if (tempOutput[j].start_time === sch.start_time && tempOutput[j].end_time === sch.end_time) {
tempOutput[j].label = tempOutput[j].label + ',' + sch.day;
}
}
}
}
//logic to identify label.
for (let i in tempOutput) {
var days = tempOutput[i].label.split(",");
var label = days[0];
var tempLDay = "";
for (let j = 1; j < days.length; j++) {
if (!tempLDay) {
label += days[j];
tempLDay = days[j];
}
//check for consecutive days
let daysDiff = allDays.indexOf(days[j - 1]) % 7 - allDays.indexOf(days[j]) % 7;
if (daysDiff == -1 || daysDiff === 1) {
label = label.replace(tempLDay, "-" + days[j]);
tempLDay = "-" + days[j]
} else {
label += "," + days[j]
tempLDay = "";
}
}
if (label == "monday-friday") {
label = "All weekdays"
} else if (label == "saturday-sunday") {
label = "Weekend"
}
output.push({
label: label,
value: tempOutput[i].start_time + ' - ' + tempOutput[i].end_time
})
}
console.log(output);

I have a similar solution on a project of mine, you could try to make any necessary changes to the code if you don't like the result.
You give an initial constants with an array of weekend and weekdays, and then comparing the inputed dated data you generate the desired output.
function formatDates(dates) {
const result = [];
const weekdays = ['monday', 'tuesday', 'wednesday', 'thursday', 'friday'];
const weekends = ['saturday', 'sunday'];
let start = 0;
let end = 0;
while (start < dates.length) {
let label = '';
let value = '';
let same = true;
end = start;
while (end < dates.length - 1 && same) {
end++;
same = dates[end].start_time === dates[end - 1].start_time && dates[end].end_time === dates[end - 1].end_time;
}
if (weekdays.includes(dates[start].day) && weekdays.includes(dates[end].day)) {
label = 'All weekdays';
value = `${dates[start].start_time} - ${dates[start].end_time}`;
} else if (weekends.includes(dates[start].day) && weekends.includes(dates[end].day)) {
label = 'Weekend';
value = `${dates[start].start_time} - ${dates[start].end_time}`;
} else if (same) {
if (weekdays.includes(dates[start].day)) {
label = `${dates[start].day[0].toUpperCase()}${dates[start].day.slice(1)} - ${dates[end].day[0].toUpperCase()}${dates[end].day.slice(1)}`;
} else if (weekends.includes(dates[start].day)) {
label = `${dates[start].day[0].toUpperCase()}${dates[start].day.slice(1)} - ${dates[end].day[0].toUpperCase()}${dates[end].day.slice(1)}`;
} else {
label = `${dates[start].day[0].toUpperCase()}${dates[start].day.slice(1)}`;
}
value = `${dates[start].start_time} - ${dates[start].end_time}`;
} else {
for (let i = start; i <= end; i++) {
result.push({
label: `${dates[i].day[0].toUpperCase()}${dates[i].day.slice(1)}`,
value: `${dates[i].start_time} - ${dates[i].end_time}`
});
}
}
if (label) {
result.push({ label, value });
}
start = end + 1;
}
return result;
}

Related

React Filtering Data with Hooks

I'm working with a dataset and want to implement a filtering option to only display what is selected (as filters do :) ). Here's the data and my code so far:
// Movies data =
[
{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
{
name: "c",
genre: "suspense",
year: "2020",
},
{
name: "d",
genre: "comedy",
year: "2020",
},
{
name: "e",
genre: "drama",
year: "2021",
},
{
name: "f",
genre: "action",
year: "2021",
},
{
name: "g",
genre: "action",
year: "2022",
},
]
and in my code, I'm have a piece of state for the API response (all data) as well as filtered data per year
import { useEffect, useState, useMemo } from 'react';
const MovieData = () => {
const [movies, setMovies] = useState([]); // all data. This will not change after API call
const [results setResults] = useState([]); // this will change based on selection
const [year, setYear] = useState({
y2019: false,
y2020: false,
y2021: false
});
// making API call
useEffect(() => {
fetch("myapiep")
.then(response => response.json())
.then(data => setMovies(data))
}, []);
// get subsets of data
const {m2019, m2020, m2021} = useMemo(() => {
const m2019 = movies.filter(m => m.year === '2019');
const m2020 = movies.filter(m => m.year === '2020');
const m2021 = movies.filter(m => m.year === '2021');
return {m2019, m2020, m2021}
});
// So far so good. Now this is where things get tricky for me
// I want to, based on the selection, modify my results array
useEffect(() => {
// update results based on movie year selected
if (year.y2019) setResults([...results, ...m2019]);
// HELP: filter out results when year is unselected
// this is not working
else {
const newArr = results.filter((movie) => !m2019.includes(movie));
}
if (year.y2020) setResults([...results, ...m2020]);
else {
const newArr = results.filter((movie) => !m2020.includes(movie));
}
if (year.y2021) setResults([...results, ...m2021]);
else {
const newArr = results.filter((movie) => !m2021.includes(movie));
}
// if none are selected, just return all movies
if (!year.y2019 && !year.y2020 && !year.y2021) {
setResults(movies);
}
}, [year]);
// I'm suppressing the logic to toggle years (y20xx) true/false for simplicity, but can add it if folks judge necessary
return (
<div>
{results.map((movie) => (
<Movie
key={uuidv4()}
name={movie.name}
genre={movie.genre}
year={movie.year}
/>
))}
</div>
)
}
What works: set filter works, for instance, setting the filter to movies made in 2019 returns
[
{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
]
What doesn't: unset the filter.
The below code snippet achieves the necessary logic (sans the React Hooks, API, and other items):
const movies = [{
name: "a",
genre: "comedy",
year: "2019",
},
{
name: "b",
genre: "drama",
year: "2019",
},
{
name: "c",
genre: "suspense",
year: "2020",
},
{
name: "d",
genre: "comedy",
year: "2020",
},
{
name: "e",
genre: "drama",
year: "2021",
},
{
name: "f",
genre: "action",
year: "2021",
},
{
name: "g",
genre: "action",
year: "2022",
}
];
const filterMyMovies = (byField = 'year', value = '2020', myMovies = movies) => (
(myMovies || [])
.filter(mov => !byField || !mov[byField] || mov[byField] === value)
);
console.log('movies in year 2020:\n', filterMyMovies());
console.log('movies in year 2019:\n', filterMyMovies('year', '2019'));
console.log('movies in genre drama:\n', filterMyMovies('genre', 'drama'));
console.log('movies with name d:\n', filterMyMovies('name', 'd'));
console.log('movies with NO FILTER:\n', filterMyMovies(null, null));
Explanation
Fairly-straightforward filtering of an array of objects, with only 1 column & 1 value. May be improvised for multi-column & multi-value filtering.
How to use this
The way to use this within React-Hooks is to invoke the 'filterMyMovies' method with the appropriate parameters when the filter-criteria changes. Suppose, the year is set to 'no-filter', then simply make call to the 'filterMyMovies' method with the first & second params as null.
Suppose we need to filter by year and then by genre as well, try something like this:
filterMyMovies('genre', 'comedy', filterMyMovies('year', '2019'));
This will return 2019 comedy movies.

Sort and group objects alphabetically by the first letter from an array in Angular?

How can I sort and group objects alphabetically by the first letter from an array in angular? I have seen the example to do this Sort and group objects alphabetically in Javascript and the exact answer and output json i am looking in Angular.
As of now My api json is like this stackblitz
Expexted api json would like this stackblitz
I have tried this but i am unable to found the solution in angular.
real Json:
employees = [
{ name: "Abigail", age: "25" },
{ name: "Axle", age: "29" },
{ name: "Brianna", age: "25" },
{ name: "Brooklyn", age: "23" },
{ name: "Camila", age: "24" },
{ name: "Charlotte", age: "28" },
{ name: "David", age: "22" }
];
expecting json after sort and group objects alphabetically by the first letter from an array would like:
[
{
"alphabet": "A",
"record": [
{ "name": "Abigail", "age": "25" },
{ "name": "Axle", "age": "29" }
]
},
{
"alphabet": "B",
"record": [
{ "name": "Brianna", "age": "25" },
{ "name": "Brooklyn", "age": "23" }
]
},
{
"alphabet": "C",
"record": [
{ "name": "Camila", "age": "24" },
{ "name": "Charlotte", "age": "28" }
]
},
{
"alphabet": "D", "record": [
{ "name": "David", "age": "22" }
]
}
]
expected output like:
A
Abigail
Axle
B
Brianna
Brooklyn
C
Camila
Charlotte
D
David
As mentioned in the comment, there is no Typescript specific way to sort and group the data. You could the JS Array#reduce to group the objects to your requirement.
Try the following
const employees = [ { name: "Abigail", age: "25" }, { name: "Axle", age: "29" }, { name: "Brianna", age: "25" }, { name: "Brooklyn", age: "23" }, { name: "Camila", age: "24" }, { name: "Charlotte", age: "28" }, { name: "David", age: "22" } ];
const output = employees
.reduce((acc, curr) => {
const idx = acc.findIndex(e => e.alphabet === curr.name[0]);
if (idx === -1) {
acc.push({ alphabet: curr.name[0], record: [curr] });
}
else {
acc[idx].record.push(curr);
acc[idx].record.sort((r1, r2) => r1.name > r2.name ? 1 : -1);
}
return acc;
}, [])
.sort((e1, e2) => e1.alphabet > e2.alphabet ? 1 : -1);
console.log(output);
It would look like following in the Stackblitz.
export class ExpansionOverviewExample {
#ViewChild(MatAccordion, { static: false }) accordion: MatAccordion;
employees = [
{ name: "Brianna", age: "25" },
{ name: "Axle", age: "29" },
{ name: "David", age: "22" },
{ name: "Brooklyn", age: "23" },
{ name: "Camila", age: "24" },
{ name: "Abigail", age: "25" },
{ name: "Charlotte", age: "28" }
];
constructor() {
this.employees = this.employees
.reduce((acc, curr) => {
const idx = acc.findIndex(e => e.alphabet === curr.name[0]);
if (idx === -1) {
acc.push({ alphabet: curr.name[0], record: [curr] });
} else {
acc[idx].record.push(curr);
acc[idx].record.sort((r1, r2) => (r1.name > r2.name ? 1 : -1));
}
return acc;
}, [])
.sort((e1, e2) => (e1.alphabet > e2.alphabet ? 1 : -1));
}
}
You could also use safe navigation operator ?. in the template so you don't get any undefined errors before the reduce is complete.
<div *ngFor="let mani of employees">
<div>
<p>{{mani?.alphabet}}</p>
<p *ngFor="let group of mani?.record"> {{ group?.name }}</p>
<hr>
</div>
</div>
I've updated your Stackblitz

Ruby set hash inside the Hash for the Array of Hashes

I am working on Rails 6 API. This is what I get
"data": [
{
"invoice_details": {
"customer_name": "Dylan Sollfrank",
"invoice_number": "1060",
"invoice_status": "paid"
}
},
{
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
},
Following is my code
def get_payment_report_activity(invoice_transactions, timezone = Time.zone.name)
invoice_details = []
transaction_details = {}
amount = {}
invoice_transactions.group_by(&:paymentable_id).each do |key, transactions|
invoice = Invoice.find key
invoice_details.push(invoice_details:{
customer_name: invoice&.customer&.fully_qualified_name&.strip,
invoice_number: invoice&.doc_number,
invoice_status: invoice&.invoice_status
})
transactions.each do |transaction|
customer = transaction&.paymentable&.customer
amount[:amount_to_pay] = transaction&.amount_to_pay.to_f
amount[:payment_fee] = transaction&.payment_fee.to_f
transaction_details[:transaction_number] = transaction&.transaction_number
transaction_details[:customer_name] = customer&.fully_qualified_name&.strip
transaction_details[:amount] = amount
transaction_details[:created_time] = Customer.time_format(transaction.created_at.in_time_zone(timezone))
transaction_details[:created_date] = Customer.date_format(transaction.created_at.in_time_zone(timezone))
transaction_details[:payment_method] = transaction&.payment_method
transaction_details[:payment_status] = transaction&.payment_status
end
invoice_details << transaction_details
end
invoice_details
end
Now I need the hash transaction details inside the invoice_details hash label as transaction_details and there can be multiple transaction details inside the invoice_details
"data": [
{
"invoice_details": {
"customer_name": "Dylan Sollfrank",
"invoice_number": "1060",
"invoice_status": "paid",
"transaction_details: [{
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
},
{
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
}]
},
"invoice_details": {
"customer_name": "Dylan Sollfrank",
"invoice_number": "1060",
"invoice_status": "paid",
"transaction_details : {
"transaction_number": "QB1589148496",
"customer_name": "Freeman Sporting Goods:55 Twin Lane",
"amount": {
"amount_to_pay": 86.4,
"payment_fee": 0.0
},
"created_time": "03:38 AM",
"created_date": "May 11, 2020",
"payment_method": "qb_payment",
"payment_status": "completed"
}
},
}
you can try like this:
def get_payment_report_activity(invoice_transactions, timezone = Time.zone.name)
invoice_details = []
invoice_transactions.group_by(&:paymentable_id).each do |key, transactions|
invoice = Invoice.find key
transaction_details = []
transactions.each do |transaction|
transaction_hash = {}
amount_hash = {}
customer = transaction&.paymentable&.customer
amount_hash[:amount_to_pay] = transaction&.amount_to_pay.to_f
amount_hash[:payment_fee] = transaction&.payment_fee.to_f
transaction_hash[:transaction_number] = transaction&.transaction_number
transaction_hash[:customer_name] = customer&.fully_qualified_name&.strip
transaction_hash[:created_time] = Customer.time_format(transaction.created_at.in_time_zone(timezone))
transaction_hash[:created_date] = Customer.date_format(transaction.created_at.in_time_zone(timezone))
transaction_hash[:payment_method] = transaction&.payment_method
transaction_hash[:payment_status] = transaction&.payment_status
transaction_hash[:amount] = amount_hash
transaction_details << transaction_hash
end
invoice_details.push(invoice_details: {
customer_name: invoice&.customer&.fully_qualified_name&.strip,
invoice_number: invoice&.doc_number,
invoice_status: invoice&.invoice_status,
transaction_details: transaction_details
})
end
invoice_details
end

react chart js skip zero value month

i have a line chart showing donations per month. however i have records showing with months without donations. my json data looks like this.
"content": [
{
"donation_amount": "10",
"avg_donation_amount": 10.0,
"transaction_count": 1,
"month": 2
},
{
"donation_amount": "60",
"avg_donation_amount": 60.0,
"transaction_count": 1,
"month": 3
},
{
"donation_amount": "1556",
"avg_donation_amount": 97.00,
"transaction_count": 3,
"month": 4
}
]
which month represents for ex: 2 is february, 3 is march, 4 is april. now i still need to show that there is no donation came from the month of january.
this is my js file
async countDonationsPerMonth(){
let URL = BASE_URL+"donors_by_month";
let x = [];
let y = [];
let item = [];
try {
const response = await fetch(URL,{
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bareer ' + this.getUserAuth()
}
})
const data = await response.json();
let content = data.content;
content.map((item, key) =>
y.push(item.donation_amount)
);
this.setState({
donation_amount: y
})
}catch(err){
console.log(err)
}
}
render() {
const data = {
labels: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'],
datasets: [
{
fill: false,
backgroundColor: 'rgba(75,192,192,0.4)',
borderColor: 'rgba(75,192,192,1)',
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
data: this.state.donation_amount
}
]
};
return (
<div>
<Card title="Campaign Donations">
<Line
data={data}
width={150}
height={40}
/>
</Card>
</div>
);
}
expected output for data[0,10,60,1556,0,0,0,0,0,0,0,0]
i still wants to push to array with zero donation_amount.
any help would be much appreciated. thanks
use this
y=Array.from(Array(12)).fill(0);
content.map((item,i) =>{y[parseInt(item.month)-1]=parseInt(item.donation_amount)});
.
output example
.
content = [{
"donation_amount": "10",
"avg_donation_amount": 10.0,
"transaction_count": 1,
"month": 2
},
{
"donation_amount": "60",
"avg_donation_amount": 60.0,
"transaction_count": 1,
"month": 3
},
{
"donation_amount": "1556",
"avg_donation_amount": 97.00,
"transaction_count": 3,
"month": 4
}
];
y = Array.from(Array(12)).fill(0);
content.map((item, i) => {
y[parseInt(item.month) - 1] = parseInt(item.donation_amount)
});
console.log(y);

how to Group By Array in Angular 4 OR 5?

i got this type of array, and i want to group by only one column (first_name) from whole array,
[
{
first_name: "Apurv",
date: "2018-01-22",
is_present: "1",
}
{
first_name: "Lucky",
date: "2018-01-22",
is_present: "0",
}
{
first_name: "Apurv",
date: "2018-01-20",
is_present: "0",
}
{
first_name: "Lucky",
date: "2018-01-20",
is_present: "1",
}
]
so how can i group by this array from "component"?
var data = [
{
first_name: "Apurv",
date: "2018-01-22",
is_present: "1",
},
{
first_name: "Lucky",
date: "2018-01-22",
is_present: "0",
},
{
first_name: "Apurv",
date: "2018-01-20",
is_present: "0",
},
{
first_name: "Lucky",
date: "2018-01-20",
is_present: "1",
}
];
var groupByName = {};
data.forEach(function (a) {
groupByName [a.first_name] = groupByName [a.first_name] || [];
groupByName [a.first_name].push({ date: a.date, is_present: a.is_present });
});
console.log(groupByName);

Resources