JavaScript:比较数组中的日期,并将每个月/每年的“价格”相加

时间:2017-12-08 13:39:34

标签: javascript arrays json sorting date

我有一个包含多个transactions的json文件,其中包含dateprice属性。现在我想比较日期,如果它们在同一个月和一年中,我想总结一下价格。

JSON:

transactions: [
{
  date: "2017-11-17",
  price: "28",
},
{
  ...
}

JavaScript的:

request.onload = function() {
  for(const transaction of request.response.transactions) {
    let year = new Date(transaction.date).getFullYear();
    let month = new Date(transaction.date).getMonth();

    console.log(year + ' ' + month);  // output: 2017-11 ...
  }
};

我试图遍历json对象,但我很难找到比较日期的解决方案。

5 个答案:

答案 0 :(得分:2)

我进行了一些实验并想出了这个解决方案:

)

答案 1 :(得分:2)

编辑:使用Object.assign而非对象传播编辑的示例。

您需要使用reduce来汇总价格。有关详细信息,请参阅注释。

const transactions = [{
    date: "2017-11-17",
    price: "28",
  },
  {
    date: "2017-12-17",
    price: "23",
  },
  {
    date: "2017-11-17",
    price: "12",
  },
  {
    date: "2017-10-17",
    price: "55",
  },
  {
    date: "2017-11-17",
    price: "09",
  },
];

const sumTransactions = (transactions) => {

  const summed = transactions.reduce((acc, current) => {
    // Get the current date object
    const date = new Date(current.date);
    // Create your key/identifier
    const key = `${date.getFullYear()}-${date.getMonth() + 1}`;
    // Retreive the previous price from the accumulator
    const previousPrice = acc[key]; // Might also return undefined
    // Create your temp current price value, and be sure to deal with numbers.
    let currentPrice = Number(current.price);
    // If you had a previous value (and not undefined)
    if (previousPrice) {
      // Add it to our value
      currentPrice += Number(previousPrice);
    }
    // Return the future accumulator value
    return Object.assign(acc, {
      [key]: currentPrice, // new values will overwrite same old values
    })
  }, {})

  // Once we have all values, get the dates, and sort them (default: earlier first)
  // Return an array of each value from the summed object to our sortedArray
  const sortedArray = Object.keys(summed).sort().map((val) => {
    return summed[val];
  });

  console.log("sortedArray", sortedArray);
};

sumTransactions(transactions);

答案 2 :(得分:0)

此解决方案使用map将日期格式化为每个对象条目的年/月格式,然后缩小以按这些分隔日期求和。

const transactions = [
  {date:"2017-11-17", price: "28",}, 
  {date:"2017-12-17", price: "28",}, 
  {date:"2017-11-17", price: "20",},
  {date:"2017-12-17", price: "2",}, 
  {date:"2017-11-17", price: "58",}, 
  {date:"2017-11-17", price: "8",}, 
  {date:"2017-10-17", price: "30",}, 
  {date:"2018-11-17", price: "1",},
];

const mapper = single => {
  let d = single.date.split('-');
  let p = Number(single.price);
  return { year: d[0], month: d[1], price: p };
}

const reducer = (group, current) => {
  let i = group.findIndex(single => (single.year == current.year && single.month == current.month));
  if (i == -1) {
    return [ ...group, current ];
  }

  group[i].price += current.price;
  return group;
};

const sumPrices = transactions.map(mapper).reduce(reducer, []);
console.log(sumPrices);
  
  

答案 3 :(得分:0)

var array = [];
for (var i = 0; i < transactions.length; i++) {
    var date = new Date(transactions[i].date);
    var ym = date.getFullYear() + "-" + date.getMonth();
    if (array[ym] == null) {
        array[ym] = 0;
    }
    array[ym] += parseInt(transactions[i].price);
}

使用此数据

var transactions = [{
                date: "2017-11-17",
                price: "28",
            },
            {
                date: "2017-12-17",
                price: "5",
            },
            {
                date: "2016-02-17",
                price: "28",
            },
            {
                date: "2015-11-17",
                price: "25",
            },
            {
                date: "2016-02-17",
                price: "12",
            },
            {
                date: "2017-11-17",
                price: "50",
            }
        ];

这将为您提供所有年 - 月重复的总和:

[
    2017-10: 78, 
    2017-11: 5, 
    2016-1: 40, 
    2015-10: 25
]

答案 4 :(得分:0)

另一个解决方案是 reduce

&#13;
&#13;
var transactions = [
  {date: "2017-11-17",price: "28"},
  {date: "2017-12-17",price: "22"},
  {date: "2017-12-17",price: "20"}
];

var result = transactions.reduce(function(acc, obj) {
  var key = obj.date.substr(0,7);
  acc[key] = (acc[key] || 0) + +obj.price;
  return acc;
}, Object.create(null));

console.log(result);
&#13;
&#13;
&#13;