LANGUAGE ยป JAVASCRIPT

Array

Basic โ€‹

js
let arr = [2, 3, 5];
arr.length;
arr = Array(size).fill(value);
Array.isArray(myvar)
let empty = Array.isArray(myvar) && myvar.length

Generating an array from an array-like object:

js
arr = Array.from(arrayLikeObject);

Destructure into simpler types:

js
const [first, ...remaining] = arr;

Methods โ€‹

MethodParamsReturn typeDescription
concatarrayarrayCreates a new array with arr1 and arr2 elements merged.
includeselementbooleanReturns true if the element exists, false otherwise.
indexOfelementnumberReturns the element's index, or -1 if not present.
joinseparatorstringConcatenates all elements using the separator and returns a string.
popelementRemoves the last element and return it.
pushelementsnumberAppend elements to an array.
shiftelementRemoves the first element and return it.
slicebeginIndex endIndexarrayReturns a shallow copy of a portion of an array. [start; end] (end not included)
sortcompareFnarraySort an array in place.
splicestartIndex deleteCount itemsarrayChanges the contents of an array by removing or replacing existing elements and/or adding new elements in place.
toSortedcompareFnarrayA copy of the array sorted.

Example:

js
arr.slice(2, 5);  // Same as arr[2:5] in python

Remove by value:

js
const index = arr.indexOf(value);
if (index !== -1) {
  arr.splice(index, 1);
}

With callback โ€‹

js
arr.map(n => n * 2)
arr.reduce((accumulator, current) => accumulator + current, initialValue)
arr.forEach((currentValue, index, array) => doSomething())
arr.find(element => element > 4)  // first found element
arr.filter(element => element > 4)  // array that satisfies the condition

To iterate an array and run it async, use:

js
// Sequence
for (const file of files) {
  const contents = await fs.readFile(file, 'utf8');
  console.log(contents);
}

// Parallel
await Promise.all(files.map(async (file) => {
  const contents = await fs.readFile(file, 'utf8')
  console.log(contents)
}));