Last active
July 11, 2019 17:09
-
-
Save cndreisbach/9644c81cf187e53c5a842620588faf4e to your computer and use it in GitHub Desktop.
JavaScript examples
This file contains 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
function compareNumeric(a, b) { | |
if (a > b) return 1; | |
if (a == b) return 0; | |
if (a < b) return -1; | |
} | |
let arr = [ 2, 1, 15 ]; | |
arr.sort(compareNumeric); | |
alert(arr); // 1, 2, 15 |
This file contains 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
function uniqueSimple (array) { | |
const result = [] | |
for (let value of array) { | |
if (!result.includes(value)) { | |
result.push(value) | |
} | |
} | |
return result | |
} | |
function uniqueComplex (array, transformer) { | |
const result = [] | |
const seen = [] | |
for (let value of array) { | |
let computed | |
if (transformer) { | |
computed = transformer(value) | |
} else { | |
computed = value | |
} | |
if (!seen.includes(computed)) { | |
seen.push(computed) | |
result.push(value) | |
} | |
} | |
return result | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment