Some Array methods are commonly used in JavaScript

Tram Ho

Array is an integral part of JavaScript projects, so today I would like to introduce some common array methods.

1. forEach

forEach method implements a callback function every time it iterates over array elements.

The following example logs out all array elements:

2. map

map method creates a new array by executing a callback function every time it iterates over the array elements.

map method does not change the original array

The following example creates a new array with each element added to 10 from the array numbers :

3. filter

filter method creates a new array with the elements passed the condition of the callback function every time it iterates over the array elements.

filter method does not change the original array

The following example creates a new array of users named ‘Harry’:

4. find

find method iterates over the array elements and returns the first element that passed the condition of the callback function, if no found element satisfies undefined .

find method does not change the original array

The following example finds the first user named ‘Harry’ in the users array:

5. findIndex

findIndex method iterates over the array elements and returns the index of the first element that passed the condition of the callback function, if no found element satisfies -1 .

findIndex method does not change the original array

The following example finds the index of the first user named ‘Harry’ in the users array:

6. some

some methods are used to test true if at least one element satisfies the condition of the callback function, otherwise false if no element satisfies the condition.

some methods do not change the original array

The following example checks to see if the characters array contains the letter ‘c’:

7. every

every method is used to test to return true if all elements meet the condition of the callback function, otherwise false if at least one element does not meet the condition.

every method does not change the original array

The following example checks to see if the characters array does not contain the letter ‘e’:

8. sort

sort method implements elements in ascending order, we can pass a compare callback function to customize sort order.

sort method will change the original array

Example sort:

9. reverse

reverse method reverses the order of the array elements.

reverse method will change the original array

Reverse example:

10. concat

concat method returns a new array by merging all the elements of the arrays together.

concat method does not change the original array

Reverse example:

Conclude

Above are the commonly used array methods, I hope to help newbies to understand and use arrays effectively in javascript. Thanks for reading the article.

Share the news now

Source : Viblo