DEV Community

Cover image for Beginner's Guide To Array In JavaScript.
kamaldeen olaide, LAWAL.
kamaldeen olaide, LAWAL.

Posted on • Updated on

Beginner's Guide To Array In JavaScript.

Ultimate Guide To Array In JavaScript

Let’s look at important data structures we have in JavaScript. Array and iterables will be looked on in this article. We will cover ways of creating array(s), how to manipulate array and some of the important array methods.

What is an array?

An array in JavaScript is zero-indexed based and a collection of ordered lists of an element specified by index. An array doesn’t have a fixed length and can store any values of different types, ranging from string, Boolean, and number, to object and array itself.

Iterables vs. Array-like Objects

**Iterables **in JavaScript can be defined as any objects with @@ itearable method that also implements the iterable protocol. And most importantly, it is an object that can be looped through with a for-of-loop.

Some of the examples of iterables are NodeList, Map, Set, and String, and not every iterable is an array.

**Array-like **are objects that use indexes to access items and have a length property. Examples of array-like objects are String and NodeList, and not all array-like objects are arrays.

Creating Arrays

There are a couple of ways of creating arrays in JavaScript. They are as follows:

Creating with a square bracket notation [];

This is by far the most popular, easy, and recommended way of creating an array in JavaScript.

From the above code, an array of numbers was created using the [] method, and inside the code, you separate the values by comma and end the code with a semicolon;

Creating an array with a special keyword new and array()

This method uses a constructor function, and it builds a new array.

The above code will produce an array of numbers with two values of each number inside it, but it gets strange if we pass one value in the array and the result will be the below result.

We then get an empty array with a length of 9. We can also remove the special new keyword and the array will work perfectly.

Creating an array with Array.of();

This method of creating an array is a special method of of() on the globally available array objects in JavaScript.

The above code is created with the Array.of() method of creating an array.

Creating an array with Array.from()

Array.from() is special because it doesn’t take multiple numbers like the above mentioned ways of creating an array. If you do, it will give an error as the output.

The above code shows an error when multiple arguments are passed through an Array.from(); instead, it takes an array-like object or an iterable, which is not a real array and converts it to a real array.

Adding and removing elements from an array

PUSH()

One of the methods of adding data to an array in JavaScript is the push() method.

The above code shows that reading was added to the end of an array of favorites with the help of the push() method.

UNSHIFT()

Unshift() is an array method used to add elements to the beginning of an array.

POP()

Pop() is used to pop or remove the last element from an array.

Pop() doesn’t return the element it removes.

SHIFT()

Shift() is an array method used to remove the first element. It is similar to pop() but removes the first element of an array.

We can as well add/replace an element inside an array with the direct index access.

SPLICE()

Splice() is a special method only available on real arrays, not on array-like or iterable objects. It is used to insert an element between two elements in an array. There are two different versions of the splice method; one takes at least two arguments while the other takes more than two arguments.

The above code shows a splice method with more than two arguments. The first argument is for specifying the start index, amount of item you want to delete is the second argument, while the third argument is what you want to insert into the element. Start at index zero, delete no items, and insert kunle into the array.

Splice can also be used for the deletion of items in an array.

The above code shows splice with two arguments and is used for the deletion of an item. The first argument is the starting index, while the second argument specifies the number of items to delete.

SLICE()

The above code shows an array with sliceMethod was created with 7 items. Then, storedResult was assigned to that created array.

The new element was pushed to the sliceMethod array, and when we console.log the output, the storedResult has the new element pushed to sliceMethod. This is the normal behavior of an object because it is a reference type, but with the slice method, we can copy array as a brand new array based on the old array.

Slice() is one of the methods we can use on a real array, just like splice(). It is used to copy an array and return a brand new array.

The above code returns a brand new array, and this is another method of copying an array since an array is, in the end, an object and reference value.

Slice() can also be used to select ranges of an array, if you want to select more than one element at the same time, but not the entire elements.

The code above shows that when we use the slice() method on the sliceMeth array, we get the result of the items from index of 1 to index of 4.

Note that the index of 5 is not included in the result.

CONCAT()

A useful method for adding element to an array and return a brand new array, which will be useful if you want to create a copy an array after adding some element to it is concat() method.

Concat() method allows us to concatenate/ add element to the end of an array, this is similar to push() method, but with concat(), it takes an array or multiple arrays and combines the new array with the old array. It doesn’t add the new as nested array to the old array but instead, pull out all the element in the new array and passes them to the element in the old array and in turn return a brand new array.

indexOf() lastIndexOf()

Whenever you have an array of information and want to find out at which indexes in the array a certain element sits, you can either replace it or do whatever you feel like doing to that element.

indexOf() method will return the value of an element in an array. The output for the above code is 2. If you have the same value more than once in an array, indexOf() will return the first value alone.

lastIndexOf() is used to search for an element within an array from the right side of the array.

The above code shows that lastIndexOf() of the value 0 returns 6.

Note: both indexOf() and lastIndex0f() only work on primitive values and not on reference types of values, as the code below shows in detail.

find() and findIndex()

To find an object in an array is easy with find() and findindex(). They both take an argument that is a function that can accept up to three arguments. The first argument is the single object in the array. The index is the second of that single object, while the third argument is the full array.

findIndex() on the other hand will not return the matching item of the array , it will only return the index.

INCLUDES()

The includes() method is used to check if an element is part of an array, though it is mostly useful for primitive values because it is used to check values only.

The above code shows the output as true because it is included in the array.

FOREACH()

forEach() is an alternative to for of loop in JavaScript, it takes a function, and the function takes up to three arguments.

The above code shows the forEach() method in action. The first argument is the singular element in the array, the second argument is the index of the array, while the third argument is all the elements in the array if you need them. This enables us to have access to the indexes of the array, unlike using a for of loop.

MAP()

Map() is one of the special methods available on a real array. It has the task of taking an array, running a function on every item in the array, and the function will now return a transformed element for every element in the array.

Map() is a really nice method of transforming an array because it makes changing an element and getting a brand new array based on the changed element super easy.

SORT() and REVERSE()

Sort() is used to sort an element in an array. By default, sort() converts every element in an array to a string and sorts this in a string logic where 2 is smaller than 4. It takes a compare function that takes two numbers and executes this function on the pairs of elements.

The above code shows that the elements in the array were sorted in descending order.

reverse() is similar to the sort method as it returns the elements of the array in ascending order.

FILTER()

filter() allows us to filter the elements in an array. Just like other high-order array methods like sort, forEach, map, and find, it takes a function which allows us to reduce the number of elements of an array based on some filter.

REDUCE()

Reduce() is one of the most complex and challenging methods in JavaScript. It is used to sum up the elements in an array. It reduces an array to a simpler value.

The above code shows the arguments as previousvalue, currentvalue, currentindex, and the arrays. It also takes another optional argument which serves as the initial value to start with.

The previousvalue will be the initial value, while the first element of the array will serve as the currentvalue.

Spread Operator (…)

The spread operator is an operator that pulls out all the elements of an array and gives them to you as a standalone list of elements.

Array Destructuring

Array destructuring is a powerful and nice syntax feature used to pull out elements from an object, array included. You begin array destructuring by inserting a square bracket on the left side of the equal sign and pointing to your array; whatever you enter in the square bracket will serve as the variable name for the array on the right side.

Conclusion

In conclusion, we have looked at arrays and iterables, covered ways of creating arrays (s), how to manipulate arrays and some of the important array methods.

In this guide, we briefly talked about the popular spread operator and array destructuring.

Happy coding..

Top comments (0)