jrTilak / lazykit

Refine your JavaScript workflows with Lazykit. A concentrated collection of lean utility functions, not a bloated library.
https://lazykit.thapatilak.com.np
MIT License
6 stars 2 forks source link

difference: find the difference between two arrays #50

Open jrTilak opened 4 months ago

jrTilak commented 4 months ago

The difference function to return an array with three elements:

An array of elements that are unique to the first array. An array of elements that are unique to the second array. An array of elements that are common to both arrays.

Here's a rough sketch of what the new function might look like:

/**
 * Finds the unique and common elements between two arrays.
 *
 * @template T - The type of elements in the arrays.
 * @param {T[]} arr1 - The first array.
 * @param {T[]} arr2 - The second array.
 * @returns {[T[], T[], T[]]} - An array containing three arrays: 
 *                              the first with elements unique to arr1, 
 *                              the second with elements unique to arr2, 
 *                              and the third with elements common to both.
 */
const difference = <T>(arr1: T[], arr2: T[]): [T[], T[], T[]] => {
  const uniqueToArr1 = arr1.filter(el => !arr2.includes(el));
  const uniqueToArr2 = arr2.filter(el => !arr1.includes(el));
  const commonToBoth = arr1.filter(el => arr2.includes(el));
  return [uniqueToArr1, uniqueToArr2, commonToBoth];
};

This is just simple implementation.