proposal-array-prototype-partition icon indicating copy to clipboard operation
proposal-array-prototype-partition copied to clipboard

Consider `groupBy` generic operation

Open souenzzo opened this issue 4 years ago • 4 comments

It's a bit more generic operation "partition"

let groupBy = (f, coll) => {
  let rf = (acc, el) => {
    let id = f(el);
    acc[id] = [... (acc[id] || []), el]
    return acc
  }
  return coll.reduce(rf , {})
}

Can be used as partition as:

let {false: f, true: t} = groupBy( x => x == 2 , [1,2,3])

Maybe should we accumulate over an actual Map allowing f return any object (?!)

souenzzo avatar Aug 28 '20 18:08 souenzzo

Good one! Will give it a little more thought and search if there's an already existing proposal.

My only concern with it is that it returns an Object instead of an array, so it kind of deviates from the Array stuff. But I like the idea nonetheless :)

joaolucasl avatar Aug 28 '20 19:08 joaolucasl

A example supporting both Objects and Maps

Array.prototype.groupBy = function (f, init = {}) {
  let rfMap = (acc, el) => {
    let id = f(el);
    let els = [... acc.get(id) || [], el];
    return acc.set(id, els);
  }
  let rfObject = (acc, el) => {
    let id = f(el);
    let els = [... (acc[id] || []), el];
    acc[id] = els;
    return acc;
  }
  return this.reduce(init instanceof Map ? rfMap : rfObject , init)
}

let {true: t} = [1,2,3].groupBy(x => x == 2)

console.log(t , [1,2,3].groupBy(x => x == 2, new Map()))

souenzzo avatar Aug 29 '20 13:08 souenzzo

groupBy is great but this

const [even, odd] = [1,2,3].partition( x => x % 2);

is much nicer than

const { 0: even, 1: odd } = Object.groupBy([1,2,3], x => x % 2)

Dagur avatar Dec 13 '23 15:12 Dagur

@Dagur

const { even, odd } = Object.groupBy([1, 2, 3], x => x % 2 ? 'odd' : 'even')

bergus avatar Dec 13 '23 16:12 bergus