$.array.setOperations

Set operations (Union, Intersection, Complement, Difference)

Union of arrays

You may want to unite between 2 or more arrays uniquely, this is why we provide helper for that. Actually, you can use spread operator to do all of that[...Array1, ...Array2, ...ArrayN], but this way will allow duplication of data and not unique.

$.array.union(array1, array2, arrayN)

// Example:
const A = [1, 2, 3, 4]
const B = [2, 3]
const C = [3, 4, 5, 6]

$.array.union(A, B, C)
//=> [1, 2, 3, 4, 5, 6]

// Or
const union = Array.from(new Set([...A, ...B, ...C]))

// to check the same items inside 2 arrays
$.array.isSuperset(A, B)
//=> true

Intersection of arrays

If you do manually you only can do intersection for just 2 arrays, but our helper can intersect multiple arrays at once.

$.array.intersection(array1, array2, array3)

// Example:
$.array.intersection(A, B, C)
//=> [3]

// Or just 2 arrays
const intersection = A.filter(i => B.includes(i))

Complement of arrays

Complement also known as difference, the complement here is to remove only the first array by the same items from other arrays, we make this helper can accept multiple arrays or more than 2 arrays here.

$.array.complement(array1, array2, arrayN)

// Example:
$.array.complement(A, B, C)
//=> [1]

// or just 2 arrays
const complement = A.filter(i => B.includes(i) === false)

// or for duplication
$.array.without(A, B)
//=> [1, 4]

Difference of arrays

Difference better known as symmetric difference, here we provide a helper for removing all the same items or elements of multiple arrays and return it as a new single array.

$.array.difference(array1, array2, arrayN)

// Example:
$.array.difference(A, B, C)
//=> [1, 2, 4, 5, 6]

or just 2 arrays (union and intersection)
const difference = union.filter(i => {
  return intersection.indexOf(i) === -1
})

Last updated