0

My data:

const data = [{
    "id": 1,
    "location": 30,
    "year": 2019
  },
  {
    "id": 2,
    "location": 15,
    "year": 2000
  },
  {
    "id": 1,
    "location": 25,
    "year": 2019
  }
];

My desired outcome:

accumluatedData = [{
    "id": [1],
    "year": 2019,
    "frequency": 2
  },
  {
    "id": [2],
    "year": 2000,
    "frequency": 1
  }
];

What I have so far (with the kind help of other stackoverflowers), is getting into an array (see code below).

However, I would like to get it into an object (as shown above).

Any suggestions? Am I on the right track? Or should I use a different route?

const data = [{
    "id": 1,
    "location": 30,
    "year": 2019
  },
  {
    "id": 2,
    "location": 15,
    "year": 2000
  },
  {
    "id": 1,
    "location": 25,
    "year": 2019
  }
];


var results = [];

for (var i = 0; i < data.length; ++i) {
  if (results[data[i].year]) {
    results[data[i].year]++;
  } else {
    results[data[i].year] = 1;
  }
};

console.log("results", results);
Ant
  • 39
  • 5
  • use an object where key is the id and do the for loop thing you did. finally get Object.values of the object – cmgchess Jun 10 '22 at 19:48
  • Will the "id" for a given year always be the same? For example would you ever have an entry in 2019 with an id other than 1? If so, what ID should `accumulatedData` contain for that year? – Daniel Beck Jun 10 '22 at 19:51
  • use `var results = {};` instead of `var results = [];` – Gabriele Petrioli Jun 10 '22 at 19:52
  • Thanks Daniel, no the ID varies, so there are entries of 2019 with 2 or 3. – Ant Jun 10 '22 at 19:53
  • Does this help with answering the Q ?.. [_"How, from an array of objects, does one group, merge and aggregate values, each task by one or more different property-names / object-keys?"_](https://stackoverflow.com/questions/72404195/how-from-an-array-of-objects-does-one-group-merge-and-aggregate-values-each/72405803#72405803) – Peter Seliger Jun 10 '22 at 19:53
  • "the ID varies, so there are entries of 2019 with 2 or 3" in that case your output data format needs to be changed, because there's no way to know which ID to include on a given entry. – Daniel Beck Jun 10 '22 at 19:55
  • 1
    anyway you can group by the combination of year+id. for example the results object can have keys like "2019|1" or "2020|3" like that – cmgchess Jun 10 '22 at 19:56
  • Thanks @DanielBeck, good point! The IDs can therefore be in an array; adding IDs as they occur. I've edited the desired outcome. – Ant Jun 10 '22 at 20:02

0 Answers0