958 B
958 B
title, type, language, tags, cover, excerpt, dateModified
| title | type | language | tags | cover | excerpt | dateModified | |
|---|---|---|---|---|---|---|---|
| Mapped array union | snippet | javascript |
|
lake-church | Returns every element from both arrays that exists at least once after applying the provided function. | 2020-10-22T20:24:44+03:00 |
Returns every element that exists in any of the two arrays at least once, after applying the provided function to each array element of both.
- Create a
Setby applying allfnto all values ofa. - Create a
Setfromaand all elements inbwhose value, after applyingfndoes not match a value in the previously created set. - Return the last set converted to an array.
const unionBy = (a, b, fn) => {
const s = new Set(a.map(fn));
return Array.from(new Set([...a, ...b.filter(x => !s.has(fn(x)))]));
};
unionBy([2.1], [1.2, 2.3], Math.floor); // [2.1, 1.2]
unionBy([{ id: 1 }, { id: 2 }], [{ id: 2 }, { id: 3 }], x => x.id)
// [{ id: 1 }, { id: 2 }, { id: 3 }]