Common Array methods in Javascript

Common Array methods in Javascript

Check For The presence of an Element With indexOf()

Since arrays can be changed, or mutated, at any time, there's no guarantee about where a particular piece of data will be on a given array, or if that element even still exists. Luckily, JavaScript provides us with another built-in method, indexOf(), that allows us to quickly and easily check for the presence of an element on an array. indexOf() takes an element as a parameter, and when called, it returns:

  • the index of that element, or
  • -1 if the element does not exist on the array.

For example:

let fruits = ['apples', 'pears', 'oranges', 'peaches', 'pears'];

fruits.indexOf('dates'); // => -1 meaning that the element is not present
fruits.indexOf('oranges'); // => 2
fruits.indexOf('pears'); // => 1

It is pretty much the same way to check for an element in a multi-dimensional array, except that we should loop into the nested array. For instance, the code below can be used to filter a nested array:

function filteredArray(arr, elem) {
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {

    if (arr[i].indexOf(elem) != -1) {
      newArr.push(arr[i]); 
    }

  }
  return newArr;
}

console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3)); // => []
console.log(filteredArray([["trumpets", 2], ["flutes", 4], ["saxophones", 2]], 2)); // => ["flutes", 4]

Add Items to an Array with push() and unshift()

Both methods take one or more elements as parameters and add those elements to the array the method is being called on; the push() method adds elements to the end of an array, and unshift() adds elements to the beginning. Consider the following:

let twentyThree = 'XXIII';
let romanNumerals = ['XXI', 'XXII'];

romanNumerals.unshift('XIX', 'XX'); // => ['XIX', 'XX', 'XXI', 'XXII'].

romanNumerals.push(twentyThree); // =>`['XIX', 'XX', 'XXI', 'XXII', 'XXIII']`.

Remove Items from an Array with pop() and shift()

Both push() and unshift() have corresponding methods that are nearly functional opposites: pop() and shift(). As you may have guessed by now, instead of adding, pop() removes an element from the end of an array, while shift() removes an element from the beginning. The key difference between pop() and shift() and their cousins push() and unshift(), is that neither method takes parameters, and each only allows an array to be modified by a single element at a time.

Let's take a look:

let greetings = ['whats up?', 'hello', 'see ya!'];

greetings.pop(); // => ['whats up?', 'hello'].

greetings.shift(); // => ['hello'].

We can also return the value of the removed element with either method like this:

let popped = greetings.pop(); // => hello

greetings would have the value [], and popped would have the value hello.

Remove Items Using splice()

splice() allows us to do just that: remove any number of consecutive elements from anywhere in an array.

splice() can take up to 3 parameters, but for now, we'll focus on just the first 2. The first two parameters of splice() are integers which represent indexes, or positions, of the array that splice() is being called upon. And remember, arrays are zero-indexed, so to indicate the first element of an array, we would use 0.

splice() first parameter represents the index on the array from which to begin removing elements, while the second parameter indicates the number of elements to delete. For example:

let array = ['today', 'was', 'not', 'so', 'great'];
array.splice(2, 2);

Here we remove 2 elements, beginning with the third element (at index 2). array would have the value ['today', 'was', 'great'].

splice() not only modifies the array it's being called on, but it also returns a new array containing the value of the removed elements:

let array = ['I', 'am', 'feeling', 'really', 'happy'];
let newArray = array.splice(3, 2); // => ['really', 'happy'].

The splice method takes arguments for the index of where to start removing items, then the number of items to remove. If the second argument is not provided, the default is to remove items through the end. However, the splice method mutates the original array it is called on. Here's an example:

const cities = ["Paris", "Madrid", "Milan", "London", "Berlin"];
cities.splice(3, 1);

Here splice returns the string London and deletes it from the cities array. cities will have the value ["Chicago", "Delhi", "Islamabad", "Berlin"].

Remove items Using the slice()

As we saw in the previous section about splice, the slice method does not mutate the original array, but returns a new one which can be saved into a variable.

Recall that the slice method takes two arguments for the indices to begin and end the slice (the end is non-inclusive), and returns those items in a new array.

So using the slice method instead of splice helps to avoid any array-mutating side effects.

function nonMutatingSplice(cities) {
  // Only change code below this line
  return cities.slice(0,3); // first three element in the array

  // Only change code above this line
}

const inputCities = ["Chicago", "Delhi", "Islamabad", "London", "Berlin"];
nonMutatingSplice(inputCities);

In the above example the function nonMutatingSplice() will parse through an array and return a new array (no mutation of the original array) with the first 3 items of the array.

Add Items Using splice()

Remember in the last challenge we mentioned that splice() can take up to three parameters? Well, you can use the third parameter, comprised of one or more element(s), to add to the array. This can be incredibly useful for quickly switching out an element, or a set of elements, for another.

const numbers = [10, 11, 12, 12, 15];
const startIndex = 3;
const amountToDelete = 1;

numbers.splice(startIndex, amountToDelete, 13, 14);
console.log(numbers);

The second occurrence of 12 is removed, and we add 13 and 14 at the same index. The numbers array would now be [ 10, 11, 12, 13, 14, 15 ].

Here, we begin with an array of numbers. Then, we pass the following to splice(): The index at which to begin deleting elements (3), the number of elements to be deleted (1), and the remaining arguments (13, 14) will be inserted starting at that same index. Note that there can be any number of elements (separated by commas) following amountToDelete, each of which gets inserted.

Copy Array Items Using slice()

The next method we will cover is slice(). Rather than modifying an array, slice() copies or extracts a given number of elements to a new array, leaving the array it is called upon untouched. slice() takes only 2 parameters — the first is the index at which to begin extraction, and the second is the index at which to stop extraction (extraction will occur up to, but not including the element at this index). Consider this:

let weatherConditions = ['rain', 'snow', 'sleet', 'hail', 'clear'];
let todaysWeather = weatherConditions.slice(1, 3);

todaysWeather would have the value ['snow', 'sleet'], while weatherConditions would still have ['rain', 'snow', 'sleet', 'hail', 'clear'].

In effect, we have created a new array by extracting elements from an existing array.

Copy an Array with the Spread Operator

While slice() allows us to be selective about what elements of an array to copy, among several other useful tasks, ES6's new spread operator allows us to easily copy all of an array's elements, in order, with a simple and highly readable syntax. The spread syntax simply looks like this: ...

In practice, we can use the spread operator to copy an array like so:

let thisArray = [true, true, undefined, false, null];
let thatArray = [...thisArray];

thatArray equals [true, true, undefined, false, null]. thisArray remains unchanged and thatArray contains the same elements as thisArray.

A concise example:

It may happen that you need to make a copy of an array and add it into the original array, like a photocopier machine function where we pass the array and the number of copies.

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line
   newArr.push([...arr]); // use puch and spread operator together
    // Only change code above this line
    num--;
  }
  return newArr;
}

console.log(copyMachine([1, 2, 3], 45)); // => [ [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ], [ 1, 2, 3 ] ]

In the above code the push() method and spread operator were combined in a similar way to a += operations.

Combine Two Arrays Using the concat Method

Concatenation means to join items end to end. JavaScript offers the concat method for both strings and arrays that work in the same way. For arrays, the method is called on one, then another array is provided as the argument to concat, which is added to the end of the first array. It returns a new array and does not mutate either of the original arrays. Here's an example:

[1, 2, 3].concat([4, 5, 6]);

The returned array would be [1, 2, 3, 4, 5, 6].

concat offers a way to add new items to the end of an array without any mutating side effects - compared to the push method that will touch the original array.

Combine Arrays with the Spread Operator

Another huge advantage of the spread operator is the ability to combine arrays, or to insert all the elements of one array into another, at any index. With more traditional syntaxes, we can concatenate arrays, but this only allows us to combine arrays at the end of one, and at the start of another. Spread syntax makes the following operation extremely simple:

let thisArray = ['sage', 'rosemary', 'parsley', 'thyme'];
let thatArray = ['basil', 'cilantro', ...thisArray, 'coriander'];

thatArray would have the value ['basil', 'cilantro', 'sage', 'rosemary', 'parsley', 'thyme', 'coriander'].

Find an item from an array/object with the Array.find method

One of the array methods which finds the first matched values from an array:

const data = [{
        type: 'data1',
        name: 'abc'
    },
    {
        type: 'data2',
        name: 'cde'
    },
    {
        type: 'data1',
        name: 'fgh'
    },
];

function datafinddata(name) {
    for (let i = 0; i < data.length; ++i) {
        if (data[i].type === 'data1' && data[i].name === name) {
            return data[i];
        }
    }
}

//Shorthand
filteredData = data.find(data => data.type === 'data1' && data.name === 'fgh');

console.log(filteredData); // => { type: 'data1', name: 'fgh' }