Javascript Object месяц для расчета соответствующего значения - PullRequest
1 голос
/ 19 сентября 2019

хочу получить сумму num для каждого из повторяющихся месяцев и оставить значение для уникальных месяцев, как оно есть в этом массиве объекта

[
{num: 5000, month: "September"},
{num: 6000, month: "September"},
{num: 4500, month: "August"},
{num: 3500, month: "August"},
{num: 5000, month: "jan"},
{num: 6000, month: "feb"}

]

Ожидаемый результат

[
{num: 11000, month: "September"},
{num: 8000, month: "August"},
{num: 5000, month: "jan"},
{num: 6000, month: "feb"}

]

Ответы [ 4 ]

2 голосов
/ 19 сентября 2019

использовать reduce.

const input = [
    {num: 5000, month: "September"},
    {num: 6000, month: "September"},
    {num: 4500, month: "August"},
    {num: 3500, month: "August"},
    {num: 5000, month: "jan"},
    {num: 6000, month: "feb"}  
];

const output = Object.values(input.reduce((a, {num, month}) => {
    if(!a[month]) a[month] = {num, month};
    else { a[month].num += num;}
    
    return a;
}, {}));

console.log(output);

- Правка -

const input = [
    {num: 5000, month: "September"},
    {num: 6000, month: "September"},
    {num: 4500, month: "August"},
    {num: 3500, month: "August"},
    {num: 5000, month: "jan"},
    {num: 6000, month: "feb"}  
];

const output = Object.values(input.reduce((a, {num, month}) => {
    if(!a[month]) a[month] = {num, month, count: 1};
    else { 
        a[month].num += num;
        a[month].count += 1;
    }
    
    return a;
}, {}));

console.log(output);
1 голос
/ 19 сентября 2019
var container = [
{num: 5000, month: "September"},
{num: 6000, month: "September"},
{num: 4500, month: "August"},
{num: 3500, month: "August"},
{num: 5000, month: "jan"},
{num: 6000, month: "feb"}
];

let result = container.reduce((acc, c) => {
    let index = acc.findIndex((v) => v.month === c.month);
    index > -1 ? acc[index].num += c.num : acc.push(c);
    return acc;
}, []);
console.log(result);

Для этого вы можете использовать уменьшить .

1 голос
/ 19 сентября 2019

Вы можете reduce массив object, имеющий month как key и num как value, затем map Object.entries до нужного массива:

const arr = [
  { num: 5000, month: "September" },
  { num: 6000, month: "September" },
  { num: 4500, month: "August" },
  { num: 3500, month: "August" },
  { num: 5000, month: "jan" },
  { num: 6000, month: "feb" }
];

const reduced = arr.reduce((acc, { num, month }) => {
  acc[month] = (acc[month] || 0) + num;
  return acc;
}, {});

const result = Object.entries(reduced).map(([month, num]) => ({ num, month }));

console.log(result);

или reduce непосредственно к нужному массиву:

const arr = [
  { num: 5000, month: "September" },
  { num: 6000, month: "September" },
  { num: 4500, month: "August" },
  { num: 3500, month: "August" },
  { num: 5000, month: "jan" },
  { num: 6000, month: "feb" }
];

const result2 = arr.reduce((acc, curr) => {
  const ndx = acc.findIndex(e => e.month === curr.month);

  if (ndx > -1) {
    acc[ndx].num += curr.num;
  } else {
    acc.push(curr);
  }
  return acc;
}, []);

console.log(result2)
1 голос
/ 19 сентября 2019

Использование reduce для первоначального сокращения, а затем преобразование его обратно в исходную форму.

Возможно объединить это в один, но оказалось, что его легче понять как два отдельных шага.

const months = [{
    num: 5000,
    month: "September"
  },
  {
    num: 6000,
    month: "September"
  },
  {
    num: 4500,
    month: "August"
  },
  {
    num: 3500,
    month: "August"
  },
  {
    num: 5000,
    month: "jan"
  },
  {
    num: 6000,
    month: "feb"
  }

]

const reduced = months.reduce((result, month) => {

  if (result[month.month]) {
    result[month.month] += month.num
  } else {
    result[month.month] = month.num
  }

  return result;
}, {})

const results = Object.keys(reduced).map(key => ({
  month: key,
  num: reduced[key]
}))

console.log(results)
...