---
description: Set operations (Union, Intersection, Complement, Difference)
---

# $.array.setOperations

#### Union of arrays

![](https://223589129-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MT0SoFkd9hr5BwenNma%2F-MgiV7rcUMku9ZUxuYOd%2F-MgiZqQOWXIy5PPL7bA8%2Fset-theory-union.png?alt=media\&token=a4255dfd-1adb-4e9e-8da2-9f639897b8b4)

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

![](https://223589129-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MT0SoFkd9hr5BwenNma%2F-MgiV7rcUMku9ZUxuYOd%2F-Mgi_05JJp-LXptu8nD0%2Fset-theory-intersection.png?alt=media\&token=b8d6ffbf-bfaf-45fb-9211-c9cceab549e9)

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

![](https://223589129-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MT0SoFkd9hr5BwenNma%2F-MgiV7rcUMku9ZUxuYOd%2F-MgibnvaPOANy5Gs31eY%2Fset-theory-complement.png?alt=media\&token=8144727c-c46d-4c12-b424-6b22d2eddae4)

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

![](https://223589129-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-MT0SoFkd9hr5BwenNma%2F-MgiV7rcUMku9ZUxuYOd%2F-MgibzfYPYs-ycVMRUjP%2Fset-theory-difference.png?alt=media\&token=7f9bbef6-7208-44e0-b696-4c6af475a337)

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
})
```
