Length Group By does not work

Asked

Viewed 20 times

1

I’m using this function to group some data that comes from the API:

function groupBy(objectArray, property) {
  return objectArray.reduce(function (acc, obj) {
    var key = obj[property];
    if (!acc[key]) {
      acc[key] = [];
    }
    acc[key].push(obj);
    return acc;
  }, {});
}


var groupedYear = groupBy(this._data, 'year');

Bring the data back correctly, in this case it brings the year 2020 and 2021; inserir a descrição da imagem aqui

When I give one console.log(groupedYear.length); he returns Undefined. I need him to return the two items, which is 2020, and 2021.

1 answer

2


In this case the variable groupedYear is not an array, but an object.

Only arrays have the property length.

You want to know how many keys this object has, right? Then you can use the function Object.keys, which returns an array with all object keys.

const length = Object.keys(groupedYear).length;
  • 1

    You gave it right, I’m just waiting for the time to accept the answer. Thank you.

  • And how do I get the length within 2020 for example? to give the 13 ?

  • @Mariana in this case only use groupedYear['2020'].length.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.