Array.prototype.uniqBy

@yulia
I would like to focus on just the uniqBy style API in this case. Assuming the proposal for immutable records/tuples makes it in, uniqBy can become quite effective.

Here of some more examples of the powerful functionality uniqBy can add in conjunction on its own and with immutable records/tuples.

uniqBy (on its own):

// âś…Works with: single field, top level properties
[ {a: 1, b: 1}, {a: 1, b: 2} ].uniqBy(x => x.a); // [ {a: 1, b: 1} ]
[ {a: 1, b: 1}, {a: 1, b: 2} ].uniqBy(x => x.b); // [ {a: 1, b: 1}, {a: 1, b: 2} ]

// âś…Works with: single field, nested properties
[ {a: 1, b: {c: 2}}, {a: 2, b: {c: 2}} ].uniqBy(x => x.b.c); // [ {a: 1, b: {c: 2}} ]

// ❌Doesn’t work with multiple fields
[ {a: 1, b: 1}, {a: 1, b: 1} ].uniqBy(x => { return { 'a': x.a, 'b': x.b }}); // [ {a: 1, b: 1}, {a: 1, b: 1} ]
// Incorrect result because using wrong equality comparison, should yield: [ {a: 1, b: 1} ]

uniqBy (with immutable records/tuples):

// âś…Works with previous examples above
[ {a: 1, b: 1}, {a: 1, b: 2} ].uniqBy(x => x.a); // [ {a: 1, b: 1} ]
[ {a: 1, b: 1}, {a: 1, b: 2} ].uniqBy(x => x.b); // [ {a: 1, b: 1}, {a: 1, b: 2} ]
[ {a: 1, b: {c: 2}}, {a: 2, b: {c: 2}} ].uniqBy(x => x.b.c); // [ {a: 1, b: {c: 2}} ]

// âś…Works with single fields (using immutable records)
[ {a: 1, b: 1}, {a: 1, b: 2} ].uniqBy(x => #[ x.a ]); // [ {a: 1} ]

// âś…Works with multiple fields (using immutable records)
[ {a: 1, b: 1}, {a: 1, b: 2} ].uniqBy(x => #[ x.a, x.b ]); // [ {a: 1, b: 1}, {a: 1, b: 2} ]
1 Like