Array Methods

10 May, 2020 - 6 min read

Arrays have many useful methods.

  • They are objects that are used to store lists of items.
  • Elements inside can be of any data type, each one is accessed by it's index.
  • They have a length property that indicates how many items are in the array.
//How to create an array
let learningHowToCode = ["stressed", "scared", "overwhelmed", "tired"]

A queue is one of the most common uses of an array. In computer science, this means an ordered collection of elements. Arrays in JavaScript can work both as a queue and as a stack. They allow you to add/remove elements both to/from the beginning or the end.

According to Wikipedia a double-ended queue (abbreviated to deque, pronounced deck[1]) is an abstract data type that generalizes a queue, for which elements can be added to or removed from either the front (head) or back (tail).

  • push method : adds elements to the end of the array

    let newJourney = learningHowToCode.push('Rewarding')
  • pop method : removes the last element and returns that element only

    let mainGoal = learningHowToCode.pop('Rewarding')
  • unshift : adds the element to the beginning of an array

    let focus = learningHowToCode.unshift('Takes time')
  • shift : extracts the first element and returns it

    let reminder = learningHowToCode.shift('Takes time')
  • If you want you access the last index you can use -1, there is a neater way to do it with splice but this is also effective
var array = [1, 2, 3, 4, 5, 6]
var val = array[array.length - 1]
  • splice : it can add, remove or replace elements.

    • You can use negative indexes, -1 is one step from the last element for example modifies the array

Syntax: arr.splice(index, deleteAmount, elem1,..anyOtherElement) How to remove elements:

let poem = ["high","Still", "I'll", "Rise"];
arr.splice(0, 1); // from index 1 (arrays are zero index based) remove 1 element
console.log(poem); // ["Still", "I'll", "Rise"]

How to add elements:

let poem = ["Still", "I'll", "Rise"];
// from index 0, delete 0, then insert "by Maya Angelou"
poem.splice(0, 0, "by Maya Angelou");
console.log(poem); // ""Still", "I'll", "Rise", "by Maya Angelou"
  • slice : returns a new array with a copy of elements that you specified (excluding the last element)

    • If you call it without arguments, it just creates a copy of an array
let soup = ["carrots", "onions", "garlic", "potatoes", "juice"];
console.log( soup.slice(0, 3) ); // "carrots", "onions", "garlic", "potatoes
console.log( soup.slice(-1) ); // juice
  • concat : creates a new array that includes values from other arrays and any other additional items
let days = ["Monday", "Tuesday"];
// create a new array from: days and adds these new elements
console.log( days.concat(["Wednesday", "Thursday"]) ); //"Monday", "Tuesday","Wednesday", "Thursday"

Iterating/Searching in an array

  • forEach : runs a function for each element in an array

    console.log(`Have a lovely day on ${item}!`)
    //Have a lovely day on Monday!
    //Have a lovely day on Tuesday!
  • Filter : creates a new array with all elements that pass the test implemented by the provided function. Filter takes in a function (that returns true or false) that is run on each element of the array. All elements that return true are kept, and false ones are thrown away.
names = ["Leanne", "Sophie", "Max", "Jorge", "Peter"]
var longNames = names.filter(function(name) {
  return name.length >= 6
console.log("Longer names: ", longNames)
  • Find : Looks for an item, if found returns true, if not, returns false. Syntax:

    let result = arr.find(function(item, index, array) {
    //stops the loop if item is found and returns the item
    //item is the element. index is its index.

    If we have an array of songs, and need to find the one with year == 2005

    let beyonceSongs = [
    {year: 2005, title: "Check On It"},
    {year: 2011, title: "I Was Here"},
    {year: 2011, title: "Love On Top"},
    {year: 2008, title: "If I Were A Boy"}, 
    let oldestSong = beyonceSongs.find(song => song.year == 2005);
    console.log(oldestSong); // {year: 2005, title: "Check On It"}
  • indexOf : returns the first index where a given element can be found, or -1 if it is not found
const tea = ['peppermint', 'chamomile', 'rooibos', 'earl grey'];
console.log(tea.indexOf('rooibos')); // expected output: 2
console.log(tea.indexOf('raspberry')); // expected output: -1
  • arr.lastIndexOf(item, from) – same, but looks for from right to left
  • arr.includes(item, from) – looks for item starting from index from, returns true if found

Changing an array

  • map : One of the most popular methods. This method calls a function for each element of an array and returns an array of results. Syntax:

    let result = arr.map(function(item, index, array) {
    // returns the new value instead of item

    For example, you can double each elements amount

    let wallet = [100, 250, 50, 5]
    var newAmount= wallet.map(cash => cash * 2)
    //if you use it as a function, make sure you return
  • sort : sorts an array, and changes element order, the default sort order is ascending. The items are sorted as strings by default. If you want to use your own sorting order, you need to supply a function as the argument of arr.sort(). modifies the array

    const months = ['March', 'Jan', 'Feb', 'Dec'];
    // expected output: Array ["Dec", "Feb", "Jan", "March"]

    I would recommend looking into the MDN docs for more information, their examples are the best.

  • reverse : reverses the order of elements in an array. modifies the array

    const numbers = [1, 2, 3, 4, 5];
    console.log('reversed numbers:', numbers);
  • reduce : used to calculate a single value based on the array.
  • reduce uses an "accumulator" whih basically means any value you want, the example used is a sum

    [1, 2, 3].reduce(function(acc, n) { return acc + n; }, 0);  // 6
    // Or written out:
    let acc = 1;
    acc = acc + 2;  // 3
    acc = acc + 3;  // 6

All in all, I do not have to go in depth with all the array methods because I can always refer to MDN Docs. Only gripe I have with it, is that I find it difficult to read sometimes. The words are either too technical or require more knowledge, with time it gets easier to read.