$ cd ~rsapkf/_

JavaScript

Last updated: Aug 5, 2020 ·

Common array operations

MDN

// Create an array
const arr = ['Chess', 'Go'] // or
const arr = new Array('Chess', 'Go') // or
const arr = 'Chess, Go'.split(', ')

// Get length of array
arr.length // 2

// Create a string from an array
const arr = ['Chess', 'Go']
arr.join(', ') // "Chess, Monopoly"
arr.toString() // "Chess,Monopoly"

// Get index of item in an array with indexOf()
const arr = ['Chess', 'Go']
arr.indexOf('Chess') // 0

// Check if array contains an item with includes()
const arr = ['Chess', 'Go']
arr.includes('Chess') // true
arr.includes('Monopoly') // false

// Add an item to end of array with push()
const arr = ['Chess', 'Go']
arr.push('Sodoku') // 3 (Returns new length)
arr // ["Chess", "Go", "Sodoku"]

// Add an item to start of array with unshift()
const arr = ['Chess', 'Go']
arr.unshift('Hex') // 3 (Returns new length)
arr // ["Hex", "Chess", "Go"]

// Remove an item from end of array with pop()
const arr = ['Chess', 'Go', 'Sodoku']
arr.pop() // Sudoku (Returns the removed item)
arr // ["Chess", "Go"]

// Remove an item from start of array with shift()
const arr = ['Chess', 'Go']
arr.shift() // Chess (Returns the removed item)
arr // ["Go"]

// Remove multiple items from end of array with splice(count)
const arr = ['Chess', 'Go', 'Hex', 'KenKen', 'Crossword']
arr.splice(-3)
// ["Hex", "KenKen", "Crossword"]
// Removes last 3 items and returns a new array with removed items only
arr // ["Chess", "Go"]

// Remove multiple items from start of array with splice(startIdx, count)
const arr = ['Chess', 'Go', 'Hex', 'KenKen', 'Crossword']
arr.splice(0, 3)
// ["Chess", "Go", "Hex"]
// Removes 3 items starting from index 0 and returns a new array with removed items only
arr // ["KenKen", "Crossword"]

// Replace multiple items in array with splice(startIdx, count, ...items)
const arr = ['Chess', 'Go', 'Monopoly', 'Hex']
arr.splice(-2, 2, 'KenKen', 'Crossword')
// ["Monopoly", "Hex"]
// Removes last 2 items and returns a new array with removed items only
arr // ["Chess", "Go", "KenKen", "Crossword"]

// Merge multiple arrays with concat()
const arr = ['Chess', 'Go']
arr.concat(['Hex', 'Sudoku'])
// ["Chess", "Go", "Hex", "Sudoku"] (Returns a new combined array)

// Reverse an array
arr.reverse() // Reverses array in-place
arr.concat().reverse() // Returns a new reversed clone

// Iterate over an array with for...of
for (const game of arr) {
  console.log(game)
}

// Call a function on each element in array with forEach()
arr.forEach((game, idx) => {
  console.log(game, idx)
})

// Create shallow copy of array
const arr = ['Chess', 'Go']
const arrCopy = [...arr] // or
const arrCopy = Array.from(arr) // or
const arrCopy = arr.slice()

// Create deep copy of array
const arrDeepCopy = JSON.parse(JSON.stringify(arr)) // or
const arrDeepCopy = structuredClone(arr)

// Flatten an array with flat()
const arr = [0, [1, 3, 5], [2, 4, 6]]
arr.flat() // [0, 1, 3, 5, 2, 4, 6]

Higher order array methods

Higher order functions are functions that can take another function as their argument, return a function when executed, or both. Some useful higher order functions in JavaScript:

find()

Find the first element in an array that passes the test specified by the provided function. If no such element is found, return undefined.

const arr = [3, 5, 11, 13, 50, 21, 67]

arr.find((item) => item % 7 == 0) // 21
arr.find((item, idx) => arr[idx + 1] < item) // 50 (First element that is followed by a smaller value than itself)
arr.find((item) => item > 100) // undefined

map()

Create a new array populated with the results of calling a provided function on every element in the calling array.

const arr = [
  { lang: 'Python', ext: 'py' },
  { lang: 'JavaScript', ext: 'js' },
  { lang: 'Haskell', ext: 'hs' },
]

arr.map((item) => '.' + item.ext)
// Array [".py", ".js", ".hs"]

filter()

Filter down a given array to just the elements that pass the test implemented by the provided function.

const arr = [180, 600, 284, 583, 23, 56, 78]

arr.filter((num) => num % 2 == 0)
// Array [180, 600, 284, 56, 78]

every()

Test whether all the elements in an array pass the test given by the provided function.

const arr = ['Monkey', 'Metal', 'Mobile', 'Orange']

arr.every((item) => item.startsWith('M')) // false
arr.every((item) => item.length >= 5) // true

some()

Test whether at least one element in an array passes the test given by the provided function.

const arr = ['You', 'look', 'beautiful', 'reading', 'this']

arr.some((item) => item == 'beautiful') // true
arr.some((item) => item.includes("ugly") // false

reduce()

Execute a callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element. An initial value can be used as the first "return value of previous calculation", otherwise the first element of the array is used as initial value and iteration starts from the second element.

// Calculate the sum of numbers in an array
const arr = [2, 3, 4, 5, 6]

const initialValue = 0 // optional, if omitted the value at index 0 (2) is used and iteration starts from 3, 4...
arr.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
)
// 20

Utils

// Copy string to clipboard
const copyToClipboard = (str) => navigator.clipboard.writeText(str)

// Capitalize a string
const capitalize = (str) => str.replace(/^\w/, (c) => c.toUpperCase())
// or
// str.charAt(0).toUpperCase() + str.slice(1);

// Reverse a string
const reverseString = (str) => [...str].reverse().join('')

// Get random item from an array
const getRandomItem = (arr) => arr[Math.floor(Math.random() * arr.length)]

// Get random number between min and max (inclusive)
const getRandomNumber = (min, max) =>
  Math.floor(Math.random() * (max - min + 1) + min)

// Get unique values from an array
const getUniqueValues = (arr) => [...new Set(arr)]

// Get sum of numbers in an array
const getSum = (arr) => arr.reduce((a, b) => a + b)

// Get average of numbers in an array
const getAverage = (arr) => arr.reduce((a, b) => a + b) / arr.length

Shuffle an array

[*]

// Durstenfeld shuffle
// Shuffles array in-place
const shuffleArray = (arr) => {
  for (let i = arr.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1))
    ;[arr[i], arr[j]] = [arr[j], arr[i]]
  }
}

// Simple shuffle (Not properly distributed and inefficient)
// arr.sort(() => 0.5 - Math.random())

Format a date string

[Intl.DateTimeFormat, toLocaleDateString]

const formatDate = (dateString) => {
  const options = {
    weekday: 'short',
    year: 'numeric',
    month: 'short',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit',
    hour12: false,
  }
  return new Intl.DateTimeFormat('en', options).format(dateString)
  // or
  // new Date(dateString).toLocaleDateString('en-US', options);
}

// Usage
formatDate('1987-07-27T12:34:56') // Mon, Jul 27, 1987, 12:34:56

Format a number

[Intl.NumberFormat]

const formatNumber = (number) => {
  const options = {
    notation: 'compact',
    compactDisplay: 'short',
  }
  return new Intl.NumberFormat('en', options).format(number)
}

// Usage
formatNumber(123456) // 123K
formatNumber(456789012) // 457M

Convert seconds to HH:MM:SS

const secToHHMMSS = (sec) => {
  let hours = Math.floor(sec / 3600)
  sec %= 3600
  let minutes = Math.floor(sec / 60)
  let seconds = Math.floor(sec % 60)

  hours = hours < 10 ? `0${hours}` : `${hours}`
  minutes = minutes < 10 ? `0${minutes}` : minutes
  seconds = seconds < 10 ? `0${seconds}` : seconds

  return `${hours}:${minutes}:${seconds}`
}

Padding a string

[padStart, padEnd]

'abc'.padStart(10) // "       abc"
'abc'.padStart(10, 'foo') // "foofoofabc"
'abc'.padStart(6, '123465') // "123abc"
'abc'.padStart(8, '0') // "00000abc"

'abc'.padEnd(10) // "abc       "
'abc'.padEnd(10, 'foo') // "abcfoofoof"
'abc'.padEnd(6, '123456') // "abc123"
'abc'.padEnd(1) // "abc"

Node.js/npm

# List all user installed packages
npm list -g --depth=0

Redirect to another website

[*]

<!-- With HTML `<meta>` tags (not recommended by W3C) -->
<meta http-equiv="refresh" content="0; URL='http://new-website.com'" />
// With JavaScript
window.location = 'http://new-website.com' // or one of these
window.location.href = 'http://new-website.com'
window.location.assign('http://new-website.com')
window.location.replace('http://new-website.com')

Misc

  • The expression (x = 5, "foo") assigns 5 to x and evaluates to foo.