uniqueArray()

Generates a unique Array from any given Array. Useful when you need a unique Array without explicitly converting to Set in your code.

Note: If using objects, you may need to include arrayContainsObjectLiterals. See footnote 2.

Arguments

Required:

_array: T[]

Optional:

{
  arrayContainsObjectLiterals: boolean, // Default is false
}

Returns

(T[]): returns a new array with only unique objects as an Array (NOT A SET).

Example

const arr = [1, 1, 1, 2, 3, 3, 4, 5, 6, 7];
console.log(uniqueArray(arr));
// => [1, 2, 3, 4, 5, 6 ,7]

const arr = ["Hello", "Hello", "Goodbye"];
console.log(uniqueArray(arr));
// => ["Hello", "Goodbye"]


// With object literals, it can get tricky. Since these are defined with a memory address,
// we dont need to use { arrayContainsObjectLiterals: true }.
const obj1 = {
  greeting: "Hello",
};
const obj2 = {
  greeting: "Bonjour",
};
const arr = [obj1, obj1, obj2, obj2];
console.log(uniqueArray(arr));
// => [{ greeting: "Hello" }, { greeting: "Bonjour" }]

// When object literals are defined within the array, they each have a seperate memory address,
// So we need to use { arrayContainsObjectLiterals: true }
const arr = [{ greeting: "Hello" }, { greeting: "Hello" }, { greeting: "Bonjour" }, { greeting: "Bonjour" }];
console.log(uniqueArray(arr, { arrayContainsObjectLiterals: true }))
// => [{ greeting: "Hello" }, { greeting: "Bonjour" }]

Note

1

The reason why arrayContainsObjectLiterals exists is because the way to check if 2 object literals are the same is more intensive, so to seperate both methods, we use the arrayContainsObjectLiterals when needed.

2

When the objects to be compared are written in the array, they each hold their own individual adress in memory. This can cause problems when comparing without arrayContainsObjectLiterals because when an object is not primitive (String, Number, Boolean, etc...), it will attempt to check it's address in memory instead of it's content. That's why this code wouldn't work:

const arr = [{ greeting: "Hello" }, { greeting: "Hello" },];
console.log(uniqueArray(arr));
// => [{ greeting: "Hello" }, { greeting: "Hello" },]

Even though the options are the same, they're defined at different memory addresses, so we need to tell the function that these have different memory addresses and to evaluate them differently.

3

Please note that this function does not accept objects that contain non-primitive types, object entries/records need to be string, number, bigint, boolean, symbol, null, undefined. It currently does not accept objects with deep-nested Objects, Functions, Dates, etc...