Skip to content

Instantly share code, notes, and snippets.

@airglow923
Last active March 9, 2021 07:29
Show Gist options
  • Save airglow923/bbba2dc99ed827a3a975c99d975c51e6 to your computer and use it in GitHub Desktop.
Save airglow923/bbba2dc99ed827a3a975c99d975c51e6 to your computer and use it in GitHub Desktop.
Make a unique array with JavaScript
// Time complexity: n(n - 1) => n^2 - n
const toUniqueArray = async (array) =>
array.reduce((acc, cur) => {
if (!acc.find((elem) => elem === cur)) acc.push(cur);
return acc;
}, []);
const toUniqueArrayIndex = async (array) => {
const uniqueIndices = [];
const uniqueElements = [];
array.map((cur, idx) => {
if (!uniqueElements.find((elem) => elem === cur)) {
uniqueIndices.push(idx);
uniqueElements.push(cur);
}
return true;
});
return { indices: uniqueIndices, elements: uniqueElements };
};
// every element of an array should be of the same type
//
// Time complexity:
// - Copying: n
// - Sorting (Timesort): n log n
// - Uniquely pushing: n
//
// Total: Amortized 2n + n log n
const toUniqueArrayUnstable = (array, type) => {
if (array.length <= 1) return [].concat(array);
// copy existing array
let sorted = [].concat(array);
// sort array based on a type
switch (type) {
case "number":
sorted.sort((lhs, rhs) => lhs - rhs);
break;
case "string":
sorted.sort((lhs, rhs) => lhs.localeCompare(rhs));
break;
default:
throw new Error(`Unsupported type: ${type}`);
}
let result = [];
let prv = sorted[0];
result.push(prv);
for (let i = 1; i < sorted.length; ++i) {
if (prv !== sorted[i]) result.push(sorted[i]);
prv = sorted[i];
}
return result;
};
@airglow923
Copy link
Author

Usage:

const res = await toUniqueArray([6, 2, 1, 4, 6, 9, 1, 2, 5, 3, 3, 5]);
console.log(res);

Output:

[6, 2, 1, 4, 9, 5, 3]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment