r/javascript • • Oct 12 '19

TIL — The power of JSON.stringify replacer parameter

https://pawelgrzybek.com/til-the-power-of-json-stringify-replacer-parameter/
378 Upvotes

42 comments sorted by

View all comments

Show parent comments

-2

u/leixiaotie Oct 12 '19

Huh, TIL. Usually using lodash.uniqBy for that. Hoping if the future ECMA added arr.uniq or arr.distinct natively.

2

u/Zephirdd Oct 12 '19

how do you think that uniqBy or your examples of uniq and distinct would be implemented?

simply throwing all the items in a Set is probably the best way to implement them nowadays lol

1

u/leixiaotie Oct 13 '19

Coming from C#, I'm taking their LINQ implementation. The syntax should be like lodash's uniqBy :

Array.uniq([iteratee=_.identity])

When iteratee is empty, it use Set implementation. Otherwise it use the iteratee to get the value. Pros - easier map to uniq:

products
  .map(k => ({ name: k.name, type: k.type })
  .uniq(k => k.name + k.type);

2

u/helloiamsomeone Oct 12 '19
const distinct = iterable => [...new Set(iterable)];

const uniqBy = (iterable, mapper) => {
  const result = [];
  const mapSet = new Set();
  
  for (const value of iterable) {
    const mappedValue = mapper(value);
    
    if (!mapSet.has(mappedValue)) {
      mapSet.add(mappedValue);
      result.push(value);
    }
  }
  
  return result;
};

That was easy