functional programming - Array of literal Objects without duplicates in ES6 using Set -
the code array without repeated items has become elegant since es6:
[...new set(array)];
that's it!
however, removing duplicates if array has elements primitive data type (string, boolean, number, ...).
what set of object literals? how make work without getting duplicates, using syntax close syntax used above?
var array=["aaa","bbb","aaa","cc","aaa","bbb"]; var out=[...new set(array)]; console.log(out) //----literal object array=[{n:"j",last:"b"},{n:"j",last:"b"}]; out=[...new set(array)]; console.log(out)
the code above produces set 2 elements, yet want have 1 in case.
i use serialize/de-serialize methodology achieve this:
[...new set(array.map( //-- serialize: (e) => `${e.n}:${e.last}` ))].map( //-- de-serialize: (e) => ({ n: `${e.split(':')[0]}`, last: `${e.split(':')[1]}` }) )
however, looking es6 built-in.
in javascript 2 objects different if not same reference, when same:
var = {}; var b = {}; console.log(a === b); // false b = a; console.log(a === b); // true
sets work similarly: unless objects added referring same thing, distinct.
a custom set
one idea make work want, create own flavour of set, i.e. myset, giving methods , properties need work set.
then in implementation keep map in internals, give key store in it. make sure objects consider same, same key in map, , stored once.
a non-efficient, straightforward way of doing that, use json.stringify(item)
key. has limitations (e.g. adding self-referencing objects make json.stringify(item)
give up), rest job.
we make myset accept additional argument: function invoke item's key value. given above idea, give default value json.stringify
.
consider implementation, testing code added it:
// implementation of special set: class myset { constructor(values = [], keyfunc = json.stringify) { // use map store values this._map = new map(); // function use generating item's key this._keyfunc = keyfunc; // add initial values (var value of [...values]) this.add(value); } size() { return this._map.size; } add(item) { // key items given function this._map.set(this._keyfunc(item), item); } has(item) { return this._map.has(this._keyfunc(item)); } *[symbol.iterator] () { (var pair of this._map) { yield pair[1]; // return item } } // etc... } // test it: array = [{n:"j",last:"b"}, {n:"j",last:"b"}]; out = [...new myset(array)]; console.log(out);
as can see, although 2 objects added set, has stored one.
Comments
Post a Comment