Array methods 😲😲

Array methods 😲😲

There are many great articles on JavaScript arrays already available around the internet. So why did I write yet another article on the same subject?

Β·

10 min read

Working with arrays could be difficult sometimes if you don't know the right methods to use, when to use them and how to use them. Knowing these help to sort of simplify (I know that's not the best word to use) coding since we use array in our day-to-day life development.

You probably have read some stuff about this method but you still do not know when using and how to use them. We shall be digging into that shortly and change that narrative for you forever 🀞.

What are array methods in JavaScript?

JavaScript array methods are built-in functions that help you manipulate an array - this manipulation includes changing the array, calculating the array values, adding or removing an element from it and so on.

There are many array methods (33 precisely!) that exist and we will not cover all in this blog. We've covered most of the important arrays used in Dad to Day Life for developers.

Hellooooo!!! Slow down a little. Thanks for doing just that. I want to let you know that we shall be getting our hands dirty with some code so that you can see firsthand how these methods work. Suffice it to say; less talk, more action.

Shall we? If your answer is a yes, then scroll downwards. If not, scroll downwards still - you'll get convinced on the way 😝😝😜

Let's get started πŸ”₯πŸ”₯

Yaay GIF - Yaay GIFs

Basic information

A pair of square brackets [] represents an array in JavaScript. All the elements in the array are comma(,) separated.

In JavaScript, arrays can be a collection of elements of any type. This means that you can create an array with elements of type String, Boolean, Number, Objects, and even other Arrays.

Here is an example of an array with four elements:

type Number, Boolean, String, and Object.

const mixedTypedArray = [100, true, 'freeCodeCamp', {}];

The position of an element in the array is known as its index. In JavaScript, the array index starts with 0, and it increases by one with each element.

So, for example, in the above array, the element 100 is at index 0, true is at index 1, 'freeCodeCamp' is at index 2, and so on.

The number of elements in the array determines its length. For example, the length of the above array is four.

Interestingly, JavaScript arrays are not of fixed length. You can change the length anytime by assigning a positive numeric value.

JavaScript Array Methods

How to Add / Remove Elements to an Array in JS

Add Elements

Yes, this is the first array method we shall be looking at.

What is it used for?
Oh, I was coming to that in a bit. I'm glad you asked😊

1.push( )

  • This method adds one or more elements to the end of the array and returns the new length of the array.

  • How about we add some smiley to the emojis, like this

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜']; 
    
    emojis.push('πŸ˜‰');
    
  • Now the emoji array is:

    
    ['πŸ˜‹', 'πŸ˜›', '😝', '😜','πŸ˜‰'];
    
  • Note: the push() the method adds an element to the end of the array.

2.unshift()

  • This method adds one or more elements to the beginning of an array and returns the new length of the array.

  • Example:

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜']; 
    
    emojis.unshift('πŸ˜‰');
    
  • Now the emoji array is:

    
    ['πŸ˜‰','πŸ˜‹', 'πŸ˜›', '😝', '😜'];
    

Remove Elements

pop( )

  • This method removes the last element from the end of the array and returns that element.

  • it returns the removed element and changes the original array.

  • Example:

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜']; 
    
    emojis.pop();//😜
    console.log(emojis);
    
  • Now the emoji array is:

    
    ['πŸ˜‹', 'πŸ˜›', '😝']
    

2.shift( )

  • This method removes the first element from an array and returns that element.

  • shift() returns the removed element and changes the original array.

  • Example:

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜']; 
    
    emojis.unshift();//πŸ˜‹
    console.log(emojis);
    
  • Now the emoji array is:

    
    ['πŸ˜›', '😝', '😜']
    

Searching in array

Now let’s cover methods that search in an array.

1. Includes()

  • You can determine the presence of an element in an array using the includes() method. If the element is found, the method returns true, and false otherwise.

  • Example:

    const animal= ['🐢', '🐱', '🦊', '🐻'];
    
    animal.includes('🐼'); // returns true
    animal.includes('🐠'); // returns false
    

2.IndexOf

  • You may want to know the index position of an element in the array.

  • You can use the indexOf() method to get that. It returns the index of the first occurrence of an element in the array.

  • If an element is not found, the indexOf() method returns -1.

  • Example:

    const animal= ['🐢', '🐱', '🦊', '🐻'];
    
    names.indexOf('🐻'); // returns 3
    names.indexOf(' 🐼 '); // returns -3
    

3.lastIndexOf

  • lastIndexOf() that helps you find the index of the last occurrence of an element in the array.

  • Like indexOf(), lastIndexOf() also returns -1 if the element is not found.

  • Example:

    const animal= ['🐢', '🐱', '🦊', '🐢'];
    
    names.indexOf('🐢'); // returns 0
    .lastIndexOf('🐢'); // returns 3
    

How to Copy and Clone an Array in JS

1.Slice()

  • You can copy and clone an array to a new array using the slice() method. Note that the slice() the method doesn't change the original array. Instead, it creates a new shallow copy of the original array.

  • splice() is used to add or remove an element(s) from an array.

  • Example:

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜']; 
    const emojisCopy = emojis.slice();
    
    Console.log(emojisCopy);//['πŸ˜‹', 'πŸ˜›', '😝', '😜']
    
    emojis === emojisCopy; // returns false
    

2.splice()

  • We can use slice() in a similar way to splice(). Although, it's a little different.

  • slice() only removes from the array and doesn't add. slice(), like the name, slices out of the array.

  • The splice() method is a swiss army knife for arrays. It can do everything: insert, remove and replace elements.

  • Syntax: arr.splice(start[, deleteCount, elem1, ..., elemN])

  • Example:

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜']; 
    emojis .splice(1, 1);// from index 1 remove 1 element
    alert(emojis);
    
    return: ['πŸ˜‹','😝', '😜']
    

How to Determine if a Value is an Array in JS

You can determine if a value is an array using the Array.isArray(value) method. The method returns true if the passed value is an array.

  • Example:

    Example:
    
    Array.isArray(['πŸ…', 'πŸ„', 'πŸ₯’', '🌽', 'πŸ₯•', 'πŸ₯‘']); // returns true
    Array.isArray('πŸ…'); // returns false
    Array.isArray({ 'tomato': 'πŸ…'}); // returns false
    Array.isArray([]); // returns true
    

Let's take a pause here. So that you can go revise with tea 🀘 🀘what we've done so far.

studio ghibli study GIF

Transform an array

Let’s move on to methods that transform and reorder an array.

1.map()

  • The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.

  • Example:

    We'll create a new array of full names of all the students in the students array.

    ```js

const fullNames = students.map((element, index) => {
  return {'fullName': element['f_name'] + ' ' + element['l_name']}
});

console.log(fullNames);

```
  • Here we see a new array with the fullName properties that are computed using the f_name and l_name properties of each student object.

2. Reverse

  • This method reverses an array in place. Element at last index will be first and the element at 0 index will be last.

  • Example:

    const emojis = ['πŸ˜‹', 'πŸ˜›', '😝', '😜'];
    console.log('emojis:', emojis);
    // expected output: "emojis:" emojis ['πŸ˜‹', 'πŸ˜›', '😝', '😜']
    
    const reversed = emojis.reverse();
    console.log('reversed:', reversed);
    // expected output: "reversed:" emojis ['😜', '😝','πŸ˜›', 'πŸ˜‹']
    

3. sort( )

  • This method is used to arrange/sort an array’s elements either in ascending or descending order.

  • The default sort() method converts the element types into strings and then sorts them.

  • the default sorting order is ascending. The sort() method changes the original array.

  • he sort() method changes the original array.

    const names = ['tom', 'alex', 'bob'];
    
    names.sort(); // returns ["alex", "bob", "tom"]
    
  • The sort() method accepts an optional comparator function as an argument. You can write a comparator function and pass it to the sort() method to override the default sorting behavior.

  • Let's now take an array of numbers and sort them in ascending and descending order using a comparator function:

    const numbers = [23, 5, 100, 56, 9, 13, 37, 10, 1]
    

    First, we'll invoke the default sort() method and see the output:

    numbers.sort();
    

    Now the sorted array is, [1, 10, 100, 13, 23, 37, 5, 56, 9]. Well, that's not the output we expect. But it happens because the default sort() method converts the elements to a string and then compares them based on the UTF-16 code unit values.

    To solve this, let's write a comparator function. Here is one for the ascending order:

    function ascendingComp(a, b){
      return (a-b);
    }
    

    Now pass this to the sort() method:

    numbers.sort(ascendingComp); // retruns [1, 5, 9, 10, 13, 23, 37, 56, 100]
    
    /* 
    
    We could also code it like,
    
    numbers.sort(function(a, b) {
      return (a-b);
    });
    
    Or, with the arrow function,
    
    numbers.sort((a, b) => (a-b));
    
    */
    

    In descending order, do this:

    numbers.sort((a, b) => (b-a));
    

4. Fill

  • This method fills the elements in an array with a static value and returns the modified array.

  • Note: that the fill() method changes the original array.

Example

const colors = ['red', 'blue', 'green'];

colors.fill('pink');
console.log(colors); // ["pink", "pink", "pink"]
  • Here is an example where we are changing only the last two elements of the array using the fill() method:
const colors = ['red', 'blue', 'green'];

colors.fill('pink', 1,3); // ["red", "pink", "pink"]

In this case, the first argument of the fill() method is the value we change with. The second argument is the start index to change. It starts with 0. The last argument is to determine where to stop filling. The max value of it could be colors.length .

5. Join

  • This method returns a new string by concatenating all of the array’s elements separated by the specified separator.

The default separator used for joining is a comma(,).

const emotions = ['πŸ™‚', '😍', 'πŸ™„', '😟'];

const joined = emotions.join();
console.log(joined); // "πŸ™‚,😍,πŸ™„,😟"
  • You can pass a separator of your choice to join the elements. Here is an example of joining the elements with a custom separator:
const joined = emotions.join('<=>');
console.log(joined); // "πŸ™‚<=>😍<=>πŸ™„<=>😟"

Invoking the join() method on an empty array returns an empty string:

[].join() // returns ""

6. Concat( )

  • This method is used to merge two or more arrays and returns a new array, without changing the existing arrays.

It is an immutable method. This means it doesn't change (mutate) existing arrays.

Let's concat two arrays.

const first = [1, 2, 3];
const second = [4, 5, 6];

const merged = first.concat(second);

console.log(merged); // [1, 2, 3, 4, 5, 6]
console.log(first); // [1, 2, 3]
console.log(second); // [4, 5, 6]
  • Using the Concat () method we can merge more than two arrays. We can merge any number of arrays with this syntax:
array.concat(arr1, arr2,..,..,..,arrN);

Here is an example:

const first = [1, 2, 3];
const second = [4, 5, 6];
const third = [7, 8, 9];

const merged = first.concat(second, third);

console.log(merged); // [1, 2, 3, 4, 5, 6, 7, 8, 9]

Summary

A cheat sheet of array methods:

  • To add/remove elements:

    • push(...items) – adds items to the end,

    • pop() – extracts an item from the end,

    • shift() – extracts an item from the beginning,

    • unshift(...items) – adds items to the beginning.

    • splice(pos, deleteCount, ...items) – at index pos deletes deleteCount elements and inserts items.

    • slice(start, end) – creates a new array, copies elements from index start till end (not inclusive) into it.

    • concat(...items) – returns a new array: copies all members of the current one and adds items to it. If any of items is an array, then its elements are taken.

  • To search among elements:

    • indexOf/lastIndexOf(item, pos) – look for item starting from position pos, return the index or -1 if not found.

    • includes(value) – returns true if the array has value, otherwise false.

  • To transform the array:

    • map(func) – creates a new array from results of calling func for every element.

    • sort(func) – sorts the array in-place, then returns it.

    • reverse() – reverses the array in-place, then returns it.

    • split/join – convert a string to array and back.

To make JavaScript array manipulation easier, we should use array methods to make our work easier and the code cleaner.

Here I am ending the blog my lovely pepople

I hope this article is useful for you, if you want to tell something about the blog, you can tell in the comment, thank you so much for reading πŸ˜‡πŸ˜‡.

Β