Skip to content

Instantly share code, notes, and snippets.

@dvlden
Last active April 13, 2019 22:03
Show Gist options
  • Save dvlden/0f66879f57d153c4b521fe3aa1dc2d3b to your computer and use it in GitHub Desktop.
Save dvlden/0f66879f57d153c4b521fe3aa1dc2d3b to your computer and use it in GitHub Desktop.
JavaScript Algorithm
// Find missing numbers in the array
const numbers = [1, 2, 7, 3, 5, 4, 9]
let missing = []
for (var i = 1; i <= Math.max(...numbers); i++) {
if (!numbers.includes(i)) {
missing.push(i)
}
}
console.log(missing) // [6, 8]
// Find min and/or max number in the array
const numbers = [-10, 7, 29, 30, 5, -10, -70]
console.log(findMinMax(numbers)) // { min: -70, max: 30 }
function findMinMax (array) {
return {
min: Math.min(...array),
max: Math.max(...array)
}
}
// Remove duplicate entries from the array
const entries = [1, 2, 3, 5, 1, 5, 9, 1, 2, 8]
console.log(uniqueEntries(entries)) // [1, 2, 3, 5, 9, 8]
function uniqueEntries (array) {
return Array.from(new Set(array))
}
// Find vowels in the string
const testString = 'Hello World'
console.log(findVowels(testString)) // ["e", "o", "o"]
function findVowels (string) {
return string.match(/[aeiou]/gi)
}
// Array chunking
const array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15]
console.log(chunkArray(array, 3))
function chunkArray (array, size) {
let output = []
let index = 0
while (index < array.length) {
output.push(array.slice(index, index + size))
index += size
}
return output
}
// Find character repeated most of the time
const sample = 'Hi there, this is just a sample!'
console.log(
getMostRepeatedCharacter(
countRepeatedCharacters(sample)
)
) // { count: 4, character: "s" }
function countRepeatedCharacters (string) {
const characters = string.replace(/\s+/g, '').split('')
let output = {}
characters.forEach(character => {
output[character] = output[character] + 1 || 1 // increment by one or start with one
})
return output
}
function getMostRepeatedCharacter (object) {
let output = { count: 0, character: null }
Object.keys(object).forEach(key => {
if (object[key] > output.count) {
output.count = object[key]
output.character = key
}
})
return output
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment