// Mutating
push() // Insert an element at the end
pop() // Remove an element from the end
unshift() // Inserts an element in the beginning
shift() // Remove first element
// Iterating
forEach() // Iterates an array
filter() // Iterates an array and result is filtered array
map() // Iterates an array and result is new array
reduce() // "Reduces" the array into single value (accumulator)
// Others
slice() // Returns desired elements in a new array
concat() // Append one or more arrays with given array
Cheat sheet: Arrays
JavaScript Arrays are a very flexible data structure and used as lists, stacks, queues, tuples (e.g. pairs), etc. Some
Using Arrays
Creating Arrays, reading and writing elements:
const arr = ['a', 'b', 'c']; // Array literal
assert.deepEqual(
arr,
[
'a',
'b',
'c', // trailing commas are ignored
]
);
assert.equal(
arr.length, 3 // number of elements
);
assert.equal(
arr[0], 'a' // read (negative indices donโt work)
);
assert.equal(
arr.at(-1), 'c' // read (negative indices work)
);
arr[0] = 'x'; // write
assert.deepEqual(
arr, ['x', 'b', 'c']
);
The lengths of Arrays, adding elements:
const arr = ['a'];
assert.equal(
arr.length, 1 // number of elements
);
arr.push('b'); // add an element (preferred)
assert.deepEqual(
arr, ['a', 'b']
);
arr[arr.length] = 'c'; // add an element (alternative)
assert.deepEqual(
arr, ['a', 'b', 'c']
);
arr.length = 1; // remove elements
assert.deepEqual(
arr, ['a']
);
Creating and filling Arrays when we canโt use Array literals (e.g. because we donโt know their lengths in advance or they are too large):
const four = 4;
// Empty Array that weโll fill later
assert.deepEqual(
new Array(four),
[ , , , ,] // four holes; last comma is ignored
);
// An Array filled with a primitive value
assert.deepEqual(
new Array(four).fill(0),
[0, 0, 0, 0]
);
// An Array filled with objects
// Why not .fill()? Weโd get single object, shared multiple times.
assert.deepEqual(
Array.from({length: four}, () => ({})),
[{}, {}, {}, {}]
);
// A range of integers
assert.deepEqual(
Array.from({length: four}, (_, i) => i),
[0, 1, 2, 3]
);