N
N
Ninja Mate2016-11-30 23:36:39
JavaScript
Ninja Mate, 2016-11-30 23:36:39

How to make such a loop for sorting JSON?

Such a task.
There is JSON

[{"date":"2015 August","value":"40"},
{"date":"2016 August","value":"473"},
{"date":"2016 July","value":"106"},
{"date":"2016 June","value":"55"},
{"date":"2016 November","value":"3"},
{"date":"2016 October","value":"2"},
{"date":"2016 September","value":"287"},
{"date":"2016 August","value":"3"},
{"date":"2016 July","value":"4"},
{"date":"2016 September","value":"5"}]

We need objects in which the data value matches to be combined into one (data remains, and value is added)
Sort the data value in ascending order and make it look like new Date
[
            { date: new Date('2016 August'), value: 24 },
            { date: new Date('2016 September'), value: 44 },
            { date: new Date('2016 November'), value: 27 },
            ...
]

Help me to understand.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
N
Nicholas, 2016-12-01
@victorzadorozhnyy

// редьюсим по полю даты
var result = array.reduce(function(result, item) {
    if (!result.hasOwnProperty(item.date) ) {
          result[item.date] = 0;
    }
    result[item.date] += parseInt(item.value, 10);
    return result;
}, {});

console.log(result);
// преобразование в массив
var resultArray = [];
Object.keys(result).forEach(function(key) {
  resultArray.push({
    date: key,
    value: result[key],
  })
});
console.log(resultArray);

https://jsfiddle.net/45ryehks/

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question