Skip to main content

JavaScript

Last updated: Mar 30, 2023 ยท
Posted in wiki#notes

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('Sudoku') // 3 (Returns new length)
arr // ["Chess", "Go", "Sudoku"]

// 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', 'Sudoku']
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
[...arr].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

// Sequence generator
const range = (start, stop, step) =>
  Array.from({ length: (stop - start) / step + 1 }, (_, i) => start + i * step)

range(0, 4, 1) // [0, 1, 2, 3, 4]
range(2, 9, 2) // [2, 4, 6, 8]

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')

Get location information from URL

const url = new URL('https://example.org:3000/path/?q=keyword#id')
console.log(url)
/*
{
  href: "https://example.org:3000/path/?q=keyword#id",
  origin: "https://example.org:3000",
  protocol: "https:",
  host: "example.org:3000",
  hostname: "example.org",
  port: "3000",
  pathname: "/path/",
  search: "?q=keyword",
  hash: "#id",
  ...
}
*/

// To get the same information for current URL, you can also use `window.location`

Misc

  • The expression (x = 5, "foo") assigns 5 to x and evaluates to foo.
  • You can write large numbers in JS using underscores like this: 1_000_000. This is equivalent to 1000000 and is easier to look at.

Submit feedback
Share on: Hacker News ยท Lobsters ยท Reddit ยท Twitter