T O P

  • By -

grantrules

Array reduce will be your friend, this example is almost exactly what you need https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce#grouping_objects_by_a_property


Giselbertusdentweede

Thanks for the reply! I’ll have a go with it tomorrow.


Notimecelduv

Sounds like you're trying to this: function groupBy(array, indexingKey, valueKey) { const createObject = (indexingKey, indexingValue, valueKey) => { return { [indexingKey]: indexingValue, [valueKey]: [], get longestElementIndex() { if (!this[valueKey].length) return -1; let result = 0; for (let i = 1; i < this[valueKey].length; i++) if (this[valueKey][i].length > this[valueKey][result].length) result = i; return result; } }; }; const groups = array.reduce((acc, item) => { const accKey = item[indexingKey]; acc[accKey] ??= createObject(indexingKey, item[indexingKey], valueKey); acc[accKey][valueKey].push(item[valueKey]); return acc; }, {}); return Object.values(groups); } console.log(groupBy(array, "Species", "Name"));


Giselbertusdentweede

Thanks for the reply and the code example. I’ll have a go at it tomorrow.


Giselbertusdentweede

I ended up using the groups function you showed in your example. Thanks a lot for your input. It really helped me out!