0

Based on great answers to the question, I've been using the following implementation:

type GroupResult<T> = { [key: string]: T[] };

function group<T>(input: Array<T>, predicate: (v: T) => string): GroupResult<T> {
    return input.reduce((acc: GroupResult<T>, value: T) => {
        (acc[predicate(value)] ||= []).push(value);
        return acc;
    }, {} as GroupResult<T>);
}

Is it possible, within the same simple approach, to add one last missing compliance for non-array (array-like) objects?

A specifically want to stick with the reduce approach, because I'm using it for iterables, not just arrays.

Array.group supports:

  • Arrays (works)
  • Sparse Arrays (works)
  • Non-array objects (doesn't work)

I need to add compliance for the last item (non-array objects):

const arrayLike = {
  length: 3,
  0: 2,
  1: 3,
  2: 4,
};

console.log(group(arrayLike, (x) => x % 2));
// { 0: [2, 4], 1: [3] }

Currently, it doesn't work.

I'm not sure why it is marked as duplicate to this question, it is very different from what I'm asking here. I'm asking how to complete that implementation to include array-like objects.

vitaly-t
  • 24,279
  • 15
  • 116
  • 138
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/250131/discussion-on-question-by-vitaly-t-complete-array-group-implementation-with-non). – sideshowbarker Dec 04 '22 at 09:30

0 Answers0