DEV Community

Cover image for How to use built-in array methods in JavaScript
Marina Yamaoto
Marina Yamaoto

Posted on

How to use built-in array methods in JavaScript

When using an array, you will find that you have to do long iterations in many situations.
Do you want to make your code readable and simple?
Can be done by using built-in objects.
There are various built-in objects in JavaScript.
In this article, I will explain how to use the built-in array methods.

What are built-in objects

At first, what are built-in objects?
Built-in objects provided from the beginning in JavaScript.
There are four built-in objects: Array, Date, Math, and String for efficient handling of these objects. Each object has special-purpose properties and methods associated with it.

Array methods

There are many array methods on the list.
let's see the top of useful methods.

"ADD & DELETE"

push()

add a new element to the end of the array. It returns the new length of the array. The original array will be modified.

what is the good thing when you use push method?
Let's see the example.

The example above shows two ways to add an element.
the first method is to specify the element number[4], which is the number added by one from the current last element number of the array you want to add and assign 'squirrel' to it.
The elements of an array do not have to be contiguous. Therefore the index of the element to be added does not have to be the current last index plus one. If the number is not the current last index, it will be null between the new element.

The second is push method.
When you use push method, you don't need to count the current last element number of the array.

But push() returns the new length of the array.
when you print the 'push', you can see the length.
So when you would like to print the new array, you have to write 'pets'.

unshift()

Add a new element or multiple elements to the top of an array and returns the number of elements after the addition. The original array will be modified.

It is used in the same way as push method, but if you are adding multiple elements at the same time, be careful about the order in which they are added.

Alphabet1 Result is adding multiple elements at the same time. The alphabet starts "A".
Alphabet2 result starts C. Because alphabet2 is adding elements in each method.

pop()

Removes the last element of an array. It returns the element and changes the length of the array. If the array is empty, it returns undefined. The original array will be modified.

shift()

Removes the top element of an array. It returns the element and changes the length of the array. If the array is empty, it returns undefined. The original array will be modified.

First In First Out (FIFO) can be created by joining with push method as described above.

slice(start, end)

It retrieves the array elements from the array at the position specified in the "start" argument to the one before the array element at the position specified in the "end" argument and returns them as a new array. The original array will not be modified. The original array will be modified.

If it only "start" argument, it retrieves the array elements from the array at the position specified in the "start" argument to the last array element and returns them as a new array.

The difference between this method and the previous methods is that it does not modify the original array. So the Before array and After array are the same length.

splice(index, deleteCount, element1, …, elementN)

Removes an element from an array or adds an element to an array, and returns the removed element. It can also replace a specified range of elements in an array with other elements.

- Remove

If you do not specify any elements to be added, the elements in the specified range will simply be removed.

- Add

If the deleteCount is specified as 0, the element to be removed will be 0 and the element specified in the argument will be added before the element specified in the start index.

- Replace

If you specify elements to be added, the elements in the specified range will be replaced.

"ORDER"

sort()

Sort array elements by string order or by specified order and return the array after sorting. The original array will be modified.

If the element is a string, it’s very simple. But if the element contains a number, be careful.

Whooops! It didn't sort!
Even if the value stored in an element is a number, it is not sorted by the size of the number, but as a string after the number has been converted to a string. Therefore, the first character is sorted first, resulting in the result as shown above.

In this case, compareFunction is useful.
CompareFunction is a method of comparing two values and switching their order one by one.

function compareFunc(a, b) {
    return a < b;
}
Enter fullscreen mode Exit fullscreen mode

In this example, it takes two arguments, "a" and "b", and returns the result of comparing "a < b" in return. By checking whether "a" is smaller than "b", the order is switched.

"<", ">", "==", and "-" can be used as comparison conditions to change the ascending or descending order.

Let's see the number example again.

Ta-dah! The numbers are now sorted!

To sort in descending order, use the following

reverce()

Sorts of array elements in reverse order. The original array will be modified.

"REPEAT"

forEach()

It executes a provided callback function once for each array element.

What is callback function?

Callback function is Functions passed as arguments.
and after the function "A" is executed, the function "B" specified in the argument can be executed.

if you want iterative processing, you can use for loop.

forEach does not require such initialization and can be written very efficiently.

The forEach method extracts the elements in the array in order from the top and calls the callback function. The callback function is called with the value of the currently fetched element, the index of the element, and the array itself as arguments.

It is also possible to retrieve the contents of an object!

"CONVERT"

map()

It executes a callback function for each element and returns the result as a new array.

In the callback function written as an argument, the value of the element received as an argument is converted to uppercase using the toUpperCase method, and the value is returned as the return value. After the same processing is done for all the elements, in turn, a new array with the returned values as elements is created and returned as the return value of the map method.

The values of the elements in the new array are all uppercase versions of the values of the elements in the original array, but the original array is unmodified because the map method does nothing to the original array. It's called "undestructive method".
for example sort(), splice(), push(), shift(), unshift(), reverse() will be modified of the original array.
It's called "destructive method".
When you want to back to the original array, if you already made "destructive method", you can't back to the original array. Sometimes it make many bugs. so please be careful to use "destructive method" in the code.

What the difference with forEach()?

You noticed these methods are very similar. What the difference between them?
the answer is "return".
forEach() is just an execution method、but map() will return the result as an array after execution.

Let's see the example.

This forEach() and map() are the same program and the result is the same.

But how is "return"?

forEach is "undefined".

Yay! Only map() has returned!
You can see that the execution result is able to get the array data as "return value".

reduce(call back(sum, element),Initial value)

Add up the values of all the elements in the array in order and finally get the total value.

The first process will result in "1 + 2", and the sum will be stored in the accumulated value, and the next process will execute "3 + 3". Total value “15".

What if the array elements contain objects?

In such a case, if you do not specify the initial value, the object that is the value of the first element will be stored as it is as the initial value, which will not produce the intended result.
Like this.

"SEARCH"

filter()

Use a callback function to determine whether or not the elements in the array meet the conditions, and create a new array with only the elements that meet the conditions.

In the callback function as the argument of the filter method, if the length of the element received as the argument is greater than 4, true is returned, otherwise false is returned. After calling the callback functions for all the elements, in turn, a new array containing the elements that returned true is created and returned as the return value of the filter method.

The filter method does not do anything to the original array, so the original array is not modified. This method is undestructive method.

indexOf(element, firstIndex)

Search the array for an element and returns its first index. If it is not found, returned -1.

there is one more character “Cat" in the string, but the program will terminate after returning the first matching position.

What happens if you specify "2" as the "firstInde"?

A second "Cat" will be output!

That's all I introduced useful array methods in built-in objects!
Enjoy coding :)

Top comments (1)

Collapse
 
727021 profile image
Andrew Schimelpfening

Array.includes() is also really useful.