// 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:
constarr= ['a','b','c']; // Array literalassert.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'; // writeassert.deepEqual( arr, ['x','b','c']);
The lengths of Arrays, adding elements:
constarr= ['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 elementsassert.deepEqual( arr, ['a']);
// Affects everyone referring to the Arrayconstarr1= ['a','b','c'];arr1.length=0;assert.deepEqual( arr1, []);// Does not affect others referring to the Arraylet arr2 = ['a','b','c'];arr2 = [];assert.deepEqual( arr2, []);
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):
constfour=4;// Empty Array that weโll fill laterassert.deepEqual(newArray(four), [ ,,,,] // four holes; last comma is ignored);// An Array filled with a primitive valueassert.deepEqual(newArray(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 integersassert.deepEqual(Array.from({length: four}, (_, i) => i), [0,1,2,3]);