Last active
March 9, 2021 07:29
-
-
Save airglow923/bbba2dc99ed827a3a975c99d975c51e6 to your computer and use it in GitHub Desktop.
Make a unique array with JavaScript
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Usage:
Output: