Menu

gitpiper

unionBy javascript Code Snippet in 2024

arrayintermediate

Last Updated: 9 October 2024

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 new Set() by applying all fn to all values of a.
  • Create a new Set() from a and all elements in b whose value, after applying fn does 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 }]

javascript snippet similar to unionBy For You in October 2024

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️

© 2024 GitPiper. All rights reserved

Rackpiper Technology Inc

Company

About UsBlogContact

Subscribe to our Newsletter

Subscribe to get resources directly to your inbox. You won't receive any spam! ✌️