如何从两个对象的特定值数组中减去或减去?

时间:2019-10-21 10:15:30

标签: javascript arrays

要傻了,我在这里问一个简单的问题,这使我花了太多时间 这是示例数据

    const demo1 = [
       { count: 156, monthCount: 1, year: 2018 },
       {  count: 165, monthCount: 2, year: 2018 },
       {  count: 103, monthCount: 3, year: 2018 },
       {  count: 60, monthCount: 4, year: 2018 }
    ]
    const data2 = [
      { count: 100, monthCount: 1, year: 2019 },
      {  count: 55, monthCount: 2, year: 2019 },
      {  count: 99, monthCount: 3, year: 2019 },
      {  count: 130, monthCount: 4, year: 2019 }
    ] 

我想获取其密钥为data2 - data1的data3 预期的输出看起来像这样

[
    {count: 56, monthCount: 1 },
    {count: 100, monthCount: 2 },
    {count: 60, monthCount: 3 },
    {count: 70, monthCount: 4 }
]

2 个答案:

答案 0 :(得分:1)

如果要减去data2 - data1,则可以通过原始JavaScript来实现。让我举一个例子。 您的数据:

const data1 = [
  { count: 156, monthCount: 1, year: 2018 },
  {  count: 165, monthCount: 2, year: 2018 },
  {  count: 103, monthCount: 3, year: 2018 },
  {  count: 60, monthCount: 4, year: 2018 }
];
const data2 = [
 { count: 100, monthCount: 1, year: 2019 },
 {  count: 55, monthCount: 2, year: 2019 },
 {  count: 99, monthCount: 3, year: 2019 },
 {  count: 130, monthCount: 4, year: 2019 }
];

一个例子:

const combined = data1.concat(data2);
console.log(`combined, not calculated`, combined);

const desired = [...combined.reduce((r, {monthCount, count}) => {
const key = monthCount;

  const item = r.get(key) || Object.assign({}, {
    count: 0,
    monthCount: monthCount
  });

  if (item.count === 0)
    item.count = -count;
  else
    item.count += +count;

  return r.set(key, item);
}, new Map).values()];

console.log(`desired: `, desired)

输出:

[
    {count: -56, monthCount: 1},
    {count: -110, monthCount: 2},
    {count: -4, monthCount: 3},
    {count: 70, monthCount: 4},
]

答案 1 :(得分:0)

const data1 = [
       { count: 156, monthCount: 1, year: 2018 },
       {  count: 165, monthCount: 2, year: 2018 },
       {  count: 103, monthCount: 3, year: 2018 },
       {  count: 60, monthCount: 4, year: 2018 }
    ]
  const data2 = [
    { count: 100, monthCount: 1, year: 2019 },
    {  count: 55, monthCount: 2, year: 2019 },
    {  count: 99, monthCount: 3, year: 2019 },
    {  count: 130, monthCount: 4, year: 2019 }
  ];

const subtractData = (arrOne, arrTwo) => {
  const newArr = []
  arrOne.forEach((elOne) => {
    arrTwo.forEach((elTwo) => {
      if(elOne.monthCount === elTwo.monthCount){
        const count = Math.abs(Number(elOne.count) - Number(elTwo.count));
        const newObj = {
         ...elOne,
         count
        }
        delete newObj.year;
        newArr.push(newObj)
      }
    })
  })

  return newArr;
}

console.log(subtractData(data1, data2))