JavaScript сума значений массива по пользователю за текущую дату
В js я абсолютный новичек. Нужно разобраться с задачей. Есть массив данных:
{
"id": 30,
"agent_id": 180,
"first_name": "Daniel",
"last_name": "Brian",
"country": null,
"amount": 3952.83,
"currency": "EUR",
"date": "2021-02-09",
"brand": "TradersPros",
"role": "Retention - morning killers Agents",
"img": "",
"is_ftd": true
},
{
"id": 31,
"agent_id": 86,
"first_name": "Ben",
"last_name": "Russo",
"country": null,
"amount": 894.96,
"currency": "EUR",
"date": "2021-02-09",
"brand": "TradersPros",
"role": "Retention - Mosad Agents",
"img": "",
"is_ftd": true
},
{
"id": 32,
"agent_id": 35,
"first_name": "Max",
"last_name": "Schmidt",
"country": null,
"amount": 214.0,
"currency": "EUR",
"date": "2021-02-09",
"brand": "TradersPros",
"role": "FTD - Minions Agents",
"img": "",
"is_ftd": true
},
{
"id": 33,
"agent_id": 178,
"first_name": "nate",
"last_name": "jansen",
"country": null,
"amount": 4959.54,
"currency": "EUR",
"date": "2021-02-09",
"brand": "TradersPros",
"role": "Retention - morning killers Agents",
"img": "",
"is_ftd": true
}
Первоначальная задача просуммировать по польователям значения ячейки amount Это я делаю с помощью следующего кода:
var counttop = result.reduce((res, el) => {
var el1 = res.find(i => i.agent_id == el.agent_id);
if (!el1) {
el1 = {
id: el.id,
agent_id: el.agent_id,
first_name: el.first_name,
last_name: el.last_name,
date: el.date,
country: el.country,
amount: 0,
currency: el.currency,
img: el.img,
role: el.role,
is_ftd: el.is_ftd
};
res.push(el1);
}
el1.amount += el.amount;
return res;
}, []);
Но теперь нужно сделать тоже саммое, просуммировать amount по пользователям но только ща текущий день. Помогите модифицировать мой код для решения этой задачи. Спасибо
Ответы (2 шт):
Добавляешь условие в find
var el1 = res.find(i => (i.agent_id == el.agent_id {AND УсловиеПоДате}));
Если я неправильно понял условия, поправьте, пожалуйста.
Ваш текущий код можно немного упростить. Ниже будет пример с вашим упрощённым вариантом и там же второй вариант с добавленной фильтрацией по дате:
const result = [
{
"id": 30,
"agent_id": 180,
"first_name": "Daniel",
"last_name": "Brian",
"country": null,
"amount": 3952.83,
"currency": "EUR",
"date": "2021-02-18",
"brand": "TradersPros",
"role": "Retention - morning killers Agents",
"img": "",
"is_ftd": true
},
{
"id": 31,
"agent_id": 86,
"first_name": "Ben",
"last_name": "Russo",
"country": null,
"amount": 894.96,
"currency": "EUR",
"date": "2021-02-18",
"brand": "TradersPros",
"role": "Retention - Mosad Agents",
"img": "",
"is_ftd": true
},
{
"id": 32,
"agent_id": 35,
"first_name": "Max",
"last_name": "Schmidt",
"country": null,
"amount": 214.0,
"currency": "EUR",
"date": "2021-02-19",
"brand": "TradersPros",
"role": "FTD - Minions Agents",
"img": "",
"is_ftd": true
},
{
"id": 33,
"agent_id": 178,
"first_name": "nate",
"last_name": "jansen",
"country": null,
"amount": 4959.54,
"currency": "EUR",
"date": "2021-02-19",
"brand": "TradersPros",
"role": "Retention - morning killers Agents",
"img": "",
"is_ftd": true
},
];
const counttop = result.reduce((res, el) => {
let el1 = res.find(({ agent_id }) => agent_id === el.agent_id);
if (!el1) res.push(el1 = {...el, amount: 0});
el1.amount += el.amount;
return res;
}, []);
console.log(counttop);
const today = new Date().toISOString().slice(0, 10);
const counttopToday = result.reduce((res, el) => {
if (el.date !== today) return res;
let el1 = res.find(({ agent_id }) => agent_id === el.agent_id);
if (!el1) res.push(el1 = {...el, amount: 0});
el1.amount += el.amount;
return res;
}, []);
console.log(counttopToday);
А ещё код можно немного ускорить: вместо того, чтобы каждый раз перебирать строящийся массив результатов в поисках нужного элемента, можно строить объект с ключами agent_id и использовать значение по ключу, а потом просто вернуть значения объекта как массив. Если не запутаетесь, можно использовать вот такой вариант:
const result = [
{
"id": 30,
"agent_id": 180,
"first_name": "Daniel",
"last_name": "Brian",
"country": null,
"amount": 3952.83,
"currency": "EUR",
"date": "2021-02-18",
"brand": "TradersPros",
"role": "Retention - morning killers Agents",
"img": "",
"is_ftd": true
},
{
"id": 31,
"agent_id": 86,
"first_name": "Ben",
"last_name": "Russo",
"country": null,
"amount": 894.96,
"currency": "EUR",
"date": "2021-02-18",
"brand": "TradersPros",
"role": "Retention - Mosad Agents",
"img": "",
"is_ftd": true
},
{
"id": 32,
"agent_id": 35,
"first_name": "Max",
"last_name": "Schmidt",
"country": null,
"amount": 214.0,
"currency": "EUR",
"date": "2021-02-19",
"brand": "TradersPros",
"role": "FTD - Minions Agents",
"img": "",
"is_ftd": true
},
{
"id": 33,
"agent_id": 178,
"first_name": "nate",
"last_name": "jansen",
"country": null,
"amount": 4959.54,
"currency": "EUR",
"date": "2021-02-19",
"brand": "TradersPros",
"role": "Retention - morning killers Agents",
"img": "",
"is_ftd": true
},
];
const counttop = Object.values(result.reduce((res, el) => {
res[el.agent_id] ??= {...el, amount: 0};
res[el.agent_id].amount += el.amount;
return res;
}, {}));
console.log(counttop);
const today = new Date().toISOString().slice(0, 10);
const counttopToday = Object.values(result.reduce((res, el) => {
if (el.date !== today) return res;
res[el.agent_id] ??= {...el, amount: 0};
res[el.agent_id].amount += el.amount;
return res;
}, {}));
console.log(counttopToday);