paint-brush
The 7 Most Useful Array Methods in JavaScriptby@pterenin
1,692 reads
1,692 reads

The 7 Most Useful Array Methods in JavaScript

by Pavel TereninAugust 30th, 2022
Read on Terminal Reader
Read this story w/o Javascript
tldt arrow

Too Long; Didn't Read

In this post I compiled a list of the most useful array methods, that can save you time and your code will look cleaner and more readable. The **forEach()** method is the most popular method to use in JavaScript. Instead of doing **for** or **while** loops to iterate through all elements of an array we can call the **forAll() method. The method has the following syntax:. Find() returns value of the element that passes the test. Map() creates a new array by transforming items of the original array to objects.
featured image - The 7 Most Useful Array Methods in JavaScript
Pavel Terenin HackerNoon profile picture

If you are working with JavaScript, you probably use Arrays a lot. Very often, you need to do some kind of manipulation with arrays or iterate through them. In this post, I compiled a list of the most useful array methods that can save you time, and your code will look cleaner and more readable.

1. ForEach

This one is the most popular method. Instead of doing for or while loops to iterate through all elements of an array, we can call the forEach() method. The forEach() method accepts function as a parameter and calls this function once for each element in the array, in order.


JavaScript

var languages = ["C#", "Java", "C++", "PHP", "JavaScript"];

languages.forEach((language, index) => {
   console.log(index+1 + ". " + language);
});

// 1. C#
// 2. Java
// 3. C++
// 4. PHP
// 5. JavaScript


forEach() method has the following syntax:

array.forEach((currentValue, index, arr) => {
 //do your stuff here
});


currentValue – the value of the current element

index – the array index of the current element

arr – the array itself


The last two parameters (index and arr) are optional.

2. Map

The map() method creates a new array by mapping each value of the original array through a transformation function. The map() method does not change the original array.


For example, we have an array of numbers and we would like to square all elements of the array.


For this purpose we can use the map() method:

var numbers = [1,2,3,4];

var squaredNumbers = numbers.map((number) => {
  return number * number;
});

console.log(squaredNumber) // => [1,4,9,16]



One more example. We want to create a new array by transforming items of the original array into objects with properties id, name, and category:

languages = ["C#", "PHP", "JavaScript"];
const mappedLanguageList = languages.map(function(language, ,index) {
  return {
    id: index + 1,
    name: language,
    category: "Programming Language"
  }; 
});


Map method creates a new array that we store in the mappedLanguageList variable; it does not update the original array.


console.log(mappedLanguageList);
// => [
//     {id: 1, name: "C#", category: "Programming Language"},
//     {id: 2, name: "PHP", category: "Programming Language"},
//     {id: 3, name: "JavaScript", category: "Programming Language"}
//    ]
 
console.log(languages);
// => ["C#", "PHP", "JavaScript"]


map() method has the following syntax:


array.map(function(currentValue, index, arr) {
    //do your mapping here
});


currentValue – the value of the current element

index – the array index of the current element

arr – the array itself


The last two parameters (index and arr) are optional.

3. Find

If you would like to find an item in an array that matches a specific condition, you could use the find() method. The find() method looks through each element of the array and returns the first one that passes the test, which is provided as a function. The function returns true (pass) or false (does not pass). And the find() method returns the value of the element that passes the test.


Let’s take a look at the following example. Here we have an array of numbers and we would like to find the first even number in the array.


[5, 7, 4, 3, 6].find(function(number) {
    return number % 2 === 0;
}); // => 4


In this example, the find() method returns 4 because it is the first element that passes the test (the function returns true). In the array, the number 6 also passes the test, but the find() method returns only the first value found and does not check the remaining values.


If no element passes the test, the find() method returns undefined.


find() method has the following syntax:

array.find(function(currentValue, index, arr) {
    //put your test here
});


currentValue – the value of the current element

index – the array index of the current element

arr – the array itself


The last two parameters (index and arr) are optional.


The find() method does not change the original array.

4. Filter

The filter() method works similarly to the find() method but returns a new array filled with all values that pass a test.


Let’s take the array of numbers from the previous example and find all even numbers in it.

[5, 7, 4, 3, 6].filter(function(number) {
    return number % 2 === 0;
});  // => [4, 6]

The filter() method created a new array that we store in the evenNumbers variable.


If no element passes the test, the filter() method returns an empty array_._


The filter() method has the following syntax:

array.filter(function(currentValue, index, arr) {
  //put your test here
});


currentValue – the value of the current element

index – the array index of the current element

arr – the array itself


The last two parameters (index and arr) are optional.


The filter() method does not change the original array.

5. Every

The every() method checks if all the elements in the array pass a test that is provided as a function. It returns a boolean value. If it finds at least one element where the function returns false, the every() method returns false.


[5, 7, 4, 3, 6].every(function(number) {
    return number % 2 === 0;
});
// returns false
[4, 8, 6].every(function(number) {
    return number % 2 === 0;
});
//returns true


The every() method has the following syntax:

array.every(function(currentValue, index, arr) {
  //put your test here
});


currentValue – the value of the current element

index – the array index of the current element

arr – the array itself


The last two parameters (index and arr) are optional.


The every() method does not change the original array.

6. Some

The some() method checks if any of the elements in an array pass a test that is provided as a function. It returns a boolean value.  If it finds at least one element where the function returns true the some() method returns true.


[5, 7, 4, 3, 6].some(function(number) {
    return number % 2 === 0;
});
// returns true



The some() method has the following syntax:

array.some(function(currentValue, index, arr) {
    //put your test here
});


currentValue – the value of the current element

index – the array index of the current element

arr – the array itself


The last two parameters (index and arr) are optional.

The some() method does not change the original array.

7. Sort

The sort() method sorts the elements of an array. By default, the sort() method sorts the values as strings in alphabetical and ascending order. This works perfectly for strings but it does not work for numeric values.


["Java", "PHP", "C#", "JavaScript", "Ruby"].sort();
// => ["C#", "Java", "JavaScript", "PHP", "Ruby"]
 
 
[12, 4, 1, 7, 3, 100].sort();
// => [1, 100, 12, 3, 4, 7]


As you see, the default behavior is not the best choice for sorting an array by a numeric value. In this case, you need to provide a “compare function”.


Ascending order:

[12, 4, 1, 7, 3, 100].sort(function(a, b){
    return a-b
});
// => [1, 3, 4, 7, 12, 100]


Descending order:

[12, 4, 1, 7, 3, 100].sort(function(a, b){
    return b-a
});
// => [100, 12, 7, 4, 3, 1]


Sorting array of objects:

var people = [
     {name: "Bill", age: 42},
     {name: "Peter", age: 35},
     {name: "Marry", age: 27}
];
 
people.sort(function(a, b) {return a.age - b.age});
// => [{name: "Marry", age: 27}, {name: "Peter", age: 35}, {name: "Bill", age: 42}];


If you would like to sort objects by string value you can use something like this:

people.sort(function (a,b) {
   if (a.name < b.name){
     return -1;
   } 
   if (a.name > b.name) {
     return 1;
   }
   return 0;
});
// => [{name: "Bill", age: 42}, {name: "Marry", age: 27}, {name: "Peter", age: 35}]


Or simply use string method localeCompare() that does the comparison for you:

people.sort(function (a,b) {
   return a.name.localeCompare(b.name)
});
// => [{name: "Bill", age: 42}, {name: "Marry", age: 27}, {name: "Peter", age: 35}]


The sort() method has the following syntax:

array.sort(compareFunction);


compareFunction – a function that defines an alternative sort order. The function should return a negative, zero, or positive value. This parameter is optional.


The sort() method changes the original array.

Conclusion

We looked at useful array methods that make code easier to read and debug. All the operations we looked at can be done with the classic for or while loops. But for and while loops luck is not selfdescribin