Basics of Javascript Arrays

Javascript Arrays

Practice: Create an array containing the squares of the numbers from 1 to 10. Then write a loop that prints them.

Standard Methods

Consult individual method pages as well as section 7.8 from the book.

Array.from
Used to construct an array from an iterable object.
Array.of
Used to construct an array from the provided arguments. You should prefer this (or the array literal notation) to using the constructor.

Iterators:

keys
Iterates over the indices of the array: for (const i of [2,3,5].keys()) { console.log(i); }
values
Iterates over the values of the array: for (const e of [2,3,5].values()) { console.log(e); }
entries
Allows you to iterate over both indices and values of an array: for (const [i, e] of [2,3,5].entries()) { console.log(i + ": " + e); }

Inserting/Removing elements:

push
adds one or more elements to the end of the array. Returns the new length of the array.
pop
removes the last element of the array and returns it.
unshift
adds one or more elements at the beginning of the array, shifting other elements to the right. Returns the new length of the array.
shift
removes the first element of the array and returns it. Shifts all other elements accordingly.

Slicing:

slice
returns a new array containing a specific range of elements from the original array.
splice
removes and/or inserts elements at a specified location in the array.

Finding:

indexOf
searches into an array looking for a specific element. Returns the index of the first match, or -1 if the search fails.
lastIndexOf
finds the last match instead.
findIndex
searches into an array looking for a specific element that satisfies a provided predicate function.

Others:

reverse
reverses the array in place.
sort
sorts the array in place. You can provide a custom sorting function, a topic we will discuss more later.
concat
returns a new array comprising of the concatenation of the original array and the arguments.
join
used for arrays of strings. Join the strings together, possibly inserting a separator.

There is another set of methods following a higher-order-function paradigm. We will discuss these in future segments.