GUIDE: Arrays Deep Dive

❯❯ Typical Array Methods

We will present some of the must know array methods to work with them effectively. We presented some of the most basic methods (like push, pop, unshift) in another guide.

Using array methods
click to copy code segment
let array = [1, 2, 3, 4, 5, 6];
/* slice returns a section of the array as subarray (not effecting the original array */
/** returns from stated index to last element, namely [3, 4, 5, 6] **/
console.log(arr.slice(2));
/** negative index counts from end of array backward. prints [3, 4, 5, 6] **/
console.log(arr.slice(-4));
/** for two arguments, returns from first argument index to second argument (excluding). prints [2, 3,  4] **/
console.log(arr.slice(1, 4));

/* splice does edit the original array, removing a subarray. behaves in a similar way as slice */
/* slice returns a section of the array as subarray (not effecting the original array */
/** original array becomes [1, 2]  **/
console.log(arr.splice(2));
/** original array becomes [1, 2] **/
console.log(arr.splice(-4));
/** original array becomes [1, 6]. Notice that splice removes inclusive **/
console.log(arr.splice(1, 4));

/* at is like indexing, and makes picking elements sometimes easier to write */
/** picking last element of arr without the method, using indexing **/
console.log(arr[arr.length - 1]);
/** using at to pick last element **/
console.log(arr.at(-1));

                              

❯❯ Looping Over Arrays Using forEach

The forEach method is a higher order function, and accepts a callback as an argument. It is more succinct to write and can manipulate the elements of an array according to the supplied callback

Using forEach too loop over an array
click to copy code segment
/** log each element of the array **/
let values = [1, 2, 3, 4, 5, 6];
values.forEach(function(elem, i, arr) {
  console.log("item number " + i + " is: " + elem);
};

                              

You should use forEach mostly for situations where an array elements are manipulating some outer other data structure in a sequential manner, or for logging, DOM manipulation. It can be used for changing the array itself, but bears no significant difference when compared to a regular for, or for .. of loops.

profile picture

WHO AM I?

Teacher
Thinker
Tinkerer