Array methods in JavaScript and when to use them

Array methods in JavaScript and when to use them

In the simplest form, Methods in Javascript are pre-written functions that tend to make our lives easier and our code cleaner. Cheesy right? Lol, I thought so too.

More seriously, they are pre-written functions that can be called on a data type to manipulate it and produce desired results.

Arrays are a type of data type in javascript that can hold other data types like strings, numbers, boolean, objects, etc. Most times, to access or interact with the contents of an array, we need to write functions to do something on the array. We might need to remove or add elements to an array, we may desire to do something with each element in an array or simply alter their arrangement. Writing functions to do any of the above may seem cool, but it isn’t necessary. This is because there are already prewritten functions in javascript that we can call out of the blues and they’d do exactly what we want. Calling these functions will make codes cleaner, shorter and readable by other developers.

So today, we will look at javascript methods that we can call on the array data type. We will also consider scenarios when their specific usage would be required.

Few things to note before we start:

  • In no particular order, we'll be discussing the following array methods:
includes(), indexOf(), isArray(), toString(), unshift(), 
valueOf(), concat(), copyWithin(), every(), entries(), 
fill(), filter(), find(), findIndex(), forEach(), from(), 
join(), keys(), lastIndexOf(), map(), pop(), push(), 
reduce(), reduceRight(), reverse(), shift(), slice(),
some(), sort(), splice().
  • This article will be split in multiple parts so as not to overwhelm the reader.
  • In this first part, we will discuss the following array methods:
    concat(), copyWithin(), every(), entries(), fill(), filter(), find()
    

Lets go!!

concat():

So let’s assume you have two different arrays that you’d want to combine into a big gigantic array, the concat() method can be called on these arrays. Depending on the order you’d want the elements of the two different arrays to be combined, array one is joined to array two using the word “concat”. See the code snippet below to understand how this is done:

let arr1 = ["a", "b", "c"];

let arr2 = ["d", "e", "f"];

let newArr = arr2.concat(arr1); 

console.log(newArr); // [ 'a', 'b', 'c', 'd', 'e', 'f' ]

The concat() method acts upon each of these arrays but does not change them, rather, it returns a new array containing elements of the two original arrays.

copyWithin():

This method lets us copy a section of an array from one position in the array to another. The copyWithin method takes in three parameters: target, start, end. Generally, this method is written as depicted below:

array.copyWithin(target, start, end)

Let's define what each parameter stands for.

  • target: The position/index to copy elements to. The original element at this index is replaced by the copied elements.
  • start: The position/index to start copying the elements
  • end: The position/index to stop copying elements. In the above, the target is a required parameter, while the rest are optional and may be omitted. When omitted, start will have a default value of index 0 meaning that it'll start copying elements from index 0. If end is omitted, it will copy every element to the last index. Let's look at some examples below:
let array1 = ['a', 'b', 'c', 'd', 'e', 'f'];
let array2 = array1.copyWithin(1, 2, 3);

console.log(array2) //[ 'a', 'c', 'c', 'd', 'e', 'f' ]

From the above, we have element c at index 2. This is the start param. We wish to copy elements from the start param to the end param, hence we'll stop copying at index 3, element d. The element at the end index is not copied. Our target index is 1, element b and we'll replace this with the copied element.

Using the same array1, let's look at another example below

let array1 = ['a', 'b', 'c', 'd', 'e', 'f'];

let array3 = array1.copyWithin(0, 2, 4)
console.log(array3) //[ 'c', 'd', 'c', 'd', 'e', 'f' ]

Here, two elements are copied from index 2 to 4. As stated above, the element at the end param doesn't get copied. The target index is 0. It is worth noting that the number of elements copied will equal the number of elements replaced. Therefore, two elements must be replaced from the target index.

As we may have noticed, the copyWithin method mutates the original array and returns a modified array of elements.

every():

This method checks every element in the array and determines whether they all meet a condition. The every() method returns a boolean value depending on whether or not all elements met a given requirement. If an element in the array does not meet the condition, the every() method returns false. But if all the elements pass the condition, the every() method returns true. The every() method does not mutate the array it is called upon. The every() method requires a callback function which states the condition each member element of the array must pass or fail. Calling the every() method on an array can be done as simply depicted below:

let array1 = [2, 3, 5, 4, 8, 6, 1];

let isBelow10 = ((x) => {
    return x < 10
});

let checkArr = array1.every(isBelow10);
console.log(checkArr) // true

In the above, elements in array1 are checked to see if they are all below 10. This returns true. But take a look at the snippet below:

let array2 = [2, 3, 5, 4, 8, 6, 20];

let isBelow10 = ((x) => {
    return x < 10
});

let checkArr = array2.every(isBelow10);
console.log(checkArr) // false

Because one element did not meet the set condition, the check fails and returns false.

entries():

The entries() method creates an iterable object off the array it was called on. In other words, the entries() method returns a new array iterator object of key/value pairs. This means that one can loop through the key/value pairs created by the entries() method. In this method, the order is usually not guaranteed. This means looping through the new array may not follow an order. So if an order is needed, one may need to sort the key/value pairs first before iterating. The entries() method does not take any parameter or arguments and does not mutate the original array it was called on.

Let's look at some examples

let fruits = ["Udara", "Ube", "Orange", "Guava", "Mango"];
let fruitsEntries = fruits.entries();

for (let entry of fruitsEntries) {
    console.log(entry) 
}
/**
  [ 0, 'Udara' ]
  [ 1, 'Ube' ]
  [ 2, 'Orange' ]
  [ 3, 'Guava' ]
  [ 4, 'Mango' ]
*/

fill():

The fill() method is used to fill up an array or replace elements in the array with a new, static value. This method mutates the original array. It has the following syntax:

array.fill(value, start, end)
  • value: This is the new static value that is used to replace elements in specified indexes of an array.
  • start: This is the index at which the replacement starts. It is an optional parameter. When it is not provided, it defaults to index 0 and every element in the array gets replaced by the value.
  • end: This is the index at which the replacement stops. It is also optional and if not provided, every element from the start index gets replaced by the provided value. It is worth noting that the element at theend index is not replaced by the value. Only elements between the start and end indexes are replaced, exclusive of element at end index.

Lets look at some examples below:

Providing only the value parameter will replace all elements in the array

let arrayOne = ["great", 1, true, "bad", "testify"];
let arrayTwo = arrayOne.fill("health");

// printing to the console:
console.log(arrayTwo); // [ 'health', 'health', 'health', 'health', 'health' ]

Supplying just the value and start index will replace every element in the array starting from the start index

let arrayOne = ["great", 1, true, "bad", "testify"];
let arrayThree = arrayOne.fill("health", 2);

// printing to the console:
console.log(arrayThree);  //[ 'great', 1, 'health', 'health', 'health' ]

Looking at the above, the start index is 2 and the element at this index is a boolean (true). All elements from this index got replaced by the value "health".

Providing all three parameters gives more control. You determine where you want this activity to start and where it ends.

let arrayOne = ["great", 1, true, "bad", "testify"];
let arrayFour = arrayOne.fill("health", 2, 4);

// printing to the console:
console.log(arrayFour); //[ 'great', 1, 'health', 'health', 'testify' ]

filter():

The filter() method is called upon each element of an array and subjected to certain test or condition described in a callback function. If an element passes the condition or test, it is placed into a new array. The filter method does not modify the original array it was called upon. Let's look at this in action with an array of random words with varying length.

let array = [
  "police",  "gate",  "extort",
  "people",  "salary",  "sermon",
  "nigerian",  "equals",  "government",
  "money",  "romances",  "bandits",  "brutality",
];

// defining callback function
let sixLetterWords = (x) => {
  return x.length === 6;
};

// calling the filter method on the array
let array2 = array.filter(sixLetterWords);

console.log(array2); 
/**
[ 'police', 'extort', 'people', 'salary', 'sermon', 'equals' ]
*/

In the above example, we filtered words with exactly six character length from the array.

Now lets filter out words with character length greater than six from the same array.


let array = [
  "police",  "gate",  "extort",
  "people",  "salary",  "sermon",
  "nigerian",  "equals",  "government",
  "money",  "romances",  "bandits",  "brutality",
];

// defining callback function
let greaterThanSixLetterWords = (x) => {
  return x.length > 6;
};

// calling the filter method on the array
let array3 = array.filter(greaterThanSixLetterWords);

console.log(array3)
/**
[ 'nigerian', 'government', 'romances', 'bandits', 'brutality' ]
*/

The filter() method produces a new array with elements that meet the specified condition. This is done without altering the original array it was called upon.

find():

The find() method is used to search for a specific element in an array that meets a condition. The value of the first element that meets the specified condition is returned and the search stops. The find() method does not mutate or alter the original array. It returns only the first element that meets its requirement. If the condition isn't met by any element, the find method returns undefined.

Using the same array example used above, lets see find() in action:

let array = [
  "police",  "gate",  "extort",
  "people",  "salary",  "sermon",
  "nigerian",  "equals",  "government",
  "money",  "romances",  "bandits",  "brutality",
];
// defining condition: elements with character length greater than six
let condition = (x) => x.length > 6 ;
let findArray = array.find(condition);
console.log(findArray); // nigerian

As soon as an element satisfied the condition for find() method, the element is returned and the activity ends immediately. If the condition is altered such that element with character length 4 is sought, we get an undefined

let array = [
  "police",  "gate",  "extort",
  "people",  "salary",  "sermon",
  "nigerian",  "equals",  "government",
  "money",  "romances",  "bandits",  "brutality",
];
// defining condition: elements with character length less than four
let condition = (x) => x.length < 4 ;
let findArray = array.find(condition);
console.log(findArray); // undefined

In this first part, we have explored the concat(), copyWithin(), every(), entries(), fill(), filter(), and find() array methods.

In the next part, we will look at join(), keys(), lastIndexOf(), includes(), indexOf(), isArray(), and toString().