Select Page

Transform an Array

1) map()
2) sort()
3) reverse()
4) join()
5) reduce()

Search in Array

6) indexOf()
7) lastIndexOf()

8) includes()
9) find()
10) filter()
11) findIndex()

Modify in Array

12) push()
13) pop()
14) shift()
15) unshift()
16) splice()
17) slice()
18) concat()

Loop the array

 19) forEach()

Check the array

 20) some()

 21) every()
Javascript Array Methods – Advanced Javascript Tutorial

Written by Asbar Ali


Arrays are one of the most essential things that you use as a programmer. So today, I’m going to be covering the most important JavaScript array methods that are going to make your coding life so much easier and more enjoyable.


01) map()

Map() take the array and convert it into a new array with the result of calling a function for every item in the array.

In the following example, we get an array which includes the number of letters of each country names by using Map() function. It takes a single parameter “country".

Click to see the Example

const allCountries = ['Sweden','Sri Lanka',  'USA', 'India', 'UK'];
const allCountryNameLength = allCountries.map((country) => {
   return country.length;
});

console.log(allCountryNameLength);

 

Result –

[6, 9, 3, 5, 2]

Note –
(i) map() creates a new array and it doesn’t affect the original array.
(i) map() will not execute if there are no items in the array.

 

array.map(function(currentValue, index, arr), thisValue)

02) sort()

sort()allows you to sort the items in the array in ascending order. This works well for string values in the array and not for numbers. But you can do it for numbers using compare function.

Here, I sort all the cities in the array to ascending order.

var cities = ["Kandy", "Delhi", "New York", "Sydney"];
cities.sort();

console.log(cities);

Result – 

["Delhi", "Kandy", "New York", "Sydney"]

Note –
(i) This changes the original array.
(ii) Provide inaccurate results for sorting numbers.

CompareFunction – // TODO


03) reverse()

reverse()allows you to reverse the order of items in the array.

Here, I sort the array in descending order.

var cities = ["Kandy", "Delhi", "New York", "Sydney"];
cities.reverse();

console.log(cities);

Result – 

["Kandy", "Delhi", "New York", "Sydney"]

Note –
(i) reverse() changes the original array.


04) join()

join()method allows you to join the all elements of an array in to a string by a seperator (default seperator is comma)

join()method will join all cities of the array using a comma and return it as a string.

var cities = ["Kandy", "Delhi", "New York", "Sydney"];
var sortedCities = cities.join();

console.log(sortedCities);

Result – 

Kandy,Delhi,New York,Sydney

05) reduce()

Reduce the array to a single value and execute the provided function for each value of an array from left to right.

So if we wanted to get the total population of all the different countries in this array, normally we would use a for loop and add the population of every single time and at the end of the for loop, you would print out the price but you can use the reduce method to do this instead.

const allCountries = [
    {name: 'Sweden', language: 'Swedish', population: 10.12},
    {name: 'Sri Lanka', language: 'Sinhala', population: 21.44},
    {name: 'USA', language: 'American English', population: 327.2},
    {name: 'India', language: 'Hindi', population: 1355.80},
    {name: 'UK', language: 'UK English', population: 66.44},
  ];

const totalPopulationOfEveryCountries = allCountries.reduce((totalPopulation, country) => {
     return country.population + totalPopulation;

  }, 0);
  
  console.log(totalPopulationOfEveryCountries);
Syntax:  array.reduce(function(total, currentValue, currentIndex, arr), initialValue)

Result – 

It doesn’t change the original array and the return value of the function is stored in an accumulator (totalPopulation).

Since it’s actually doing some operation on the array and returning a combination of all those different operations.


06) indexOf()

indexOf() method search the specific item you pass as an argument, and it returns its index position. Search from start to end.

Here, "Delhi" is repeated for 2 times and I want the index position of first"Delhi" element in the array.

var cities = ["Kandy", "Delhi", "New York", "Sydney","Delhi"];
var sortedCities = cities.indexOf("Delhi");

console.log(sortedCities);

Result – 

1

07) lastIndexOf()

lastIndexOf() method also search the specific item you pass as an argument and return its position. If that particular item presents more than once, it returns the position of the last index.

Here, "Delhi" is repeated for 2 times and I want the index position of last "Delhi" element in the array.

var cities = ["Kandy", "Delhi", "New York", "Sydney", "Delhi", "Tokyo"];
var lastIndexOfCity = cities.lastIndexOf("Delhi");

console.log(lastIndexOfCity);

Result – 

4

08) includes()

includes() method check whether the array contains you pass as an argument. It returns true if contains, and false if not.

Here, check Delhi exists in the array.

var cities = ["Kandy", "Delhi", "New York", "Sydney", "Delhi", "Tokyo"];
var isCityExist = cities.includes("Kandy");

console.log(isCityExist);

Result – 

true

09) find()

find() allows you to find a first single element in an array that passes the condition inside the function.

Let’s say we want to get the country with the name of 'India, So we can check country.name with IndiaThis is just going to return the very first item that it finds in the array that returns true for the statement that you pass inside of this find() function.

const allCountries = [
  {name: 'Sweden', language: 'Swedish', population: 10.12},
  {name: 'Sri Lanka', language: 'Sinhala', population: 21.44},
  {name: 'USA', language: 'American English', population: 327.2},
  {name: 'India', language: 'Hindi', population: 1355.80},
  {name: 'UK', language: 'UK English', population: 66.44},
];

const selectedCountry = allCountries.find((country) => {
   return country.name == "India";
});

console.log(selectedCountry);

Result – 

find() doesn’t check the remaining values if it finds the array element where the function returns a true. If it couldn’t find any element, it will return undefined.


10) filter()

filter() method filter all array elements that pass the condition inside the function and returns a new array.

Let’s assume that we want to get all the items on this list that are greater than  50 million population. So all we would need to use is the filter() method to filter out everything.

const allCountries = [
  {name: 'Sweden', language: 'Swedish', population: 10.12},
  {name: 'Sri Lanka', language: 'Sinhala', population: 21.44},
  {name: 'USA', language: 'American English', population: 327.2},
  {name: 'India', language: 'Hindi', population: 1355.80},
  {name: 'UK', language: 'UK English', population: 66.44},
];

const highestPopulatedCounties = allCountries.filter((country) => {
   return country.population>50;
});

console.log(highestPopulatedCounties);

Result – 

The great thing about filter() method is that it doesn’t change the underlying array (allCountries) that you’re filtering over.  That’s super convenient because we don’t have to worry about changing the old array when we use these new javascript array methods to create a new javascript array.


11) findIndex()

findIndex() method returns the first element of the arrray that passes the condition for the provided function.


12) push()

push() method allows us to add a new item at the end of the array and it returns the new array length.

Following array contains the list of sports and I add another sport "rugby" at the end of the array.

var sports = ["Cricket", "Baseball", "Football", "Netball"];
sports.push("Rugby");

console.log(sports);

Result – 

["Cricket", "Baseball", "Football", "Netball", "Rugby"]

13) pop()

pop() method is used to remove the last element of the array, and it returns the removed item.

Here, we use pop() method to remove the last element "Netball" from the array.

var sports = ["Cricket", "Baseball", "Football", "Netball"];
sports.push("Rugby");

console.log(sports);

Result – 

["Cricket", "Baseball", "Football"]

14) shift()

shift() method is used to remove the first item of the array, and it returns the remove item.

Following array contains the list school facilities and use shift() method to remove the "Laboratory" facility from the beginning of the array.

var schoolFacilities = ["Laboratory", "Playground", "Library", "Science lab"];
schoolFacilities.shift();

console.log(schoolFacilities);

Result – 

["Playground", "Library", "Science lab"]

15) unshift()

unshift() method is used to add a new item to the beginning of the array, and it returns the new array length.

Following "schoolFacilities" array, use unshift() method to add 2 more facilities.

var schoolFacilities = ["Laboratory", "Playground", "Library", "Science lab"];
schoolFacilities.unshift("Office", "Class Rooms");

console.log(schoolFacilities);

Result – 

["Office", "Class Rooms", "Laboratory", "Playground", "Library", "Science lab"]

16) splice()

splice() method is used to add or remove mulitple items to the array and it returns all removed items. Original array will be changed.

Following "jsFrameworks" array, if you want to add 2 more other JS frameworks to the index 2 and no need to remove items after index 2, do like this,

var jsFrameworks = ["angular", "react native", "vue js"];

jsFrameworks.splice(2, 0, "node js", "backbone js"); console.log(jsFrameworks);

Result – 

["angular", "react native","node js", "backbone js", "vue js"];

17) slice()

slice() method returns the selected items in an array and return them in a new array.

Following "jsFrameworks" array, if you want to slice first and second elements, use slice() method and pass the index of first and second elements as below.

var jsFrameworks = ["angular", "react native", "vue js", "node js", "backbone js"];

var newSlicedFrameworks = jsFrameworks.slice(1, 3);

console.log(newSlicedFrameworks);

Result – 

[ "react native", "vue js"]

18) concat()

concat() method is used to join 2 or more arrays and it returns a new array with those values of joined arrays.

Here, we have 3 arrays and need to join all of them and convert it to a string value. So use concat() method will do it as below,

var frontEndLang = ["react js", "node js"];
var mobileLang = ["android", "iOS"];
var backEndLang = ["node js", ".NET core"];

var allFrameworks = frontEndLang.concat(mobileLang, backEndLang);

console.log(allFrameworks);

Result – 

"react js", "node js", "android", "iOS", "node js", ".NET core"

19) foreach()

foreach() calls a function for each element in the array and does not return anything.  Very similarly to a for() loop but foreach take a function instead.

We have our first parameter country just like before and we could use any attribute in country object for this below example. 

  const allCountries = [
    {name: 'Sweden', language: 'Swedish', population: 10.12},
    {name: 'Sri Lanka', language: 'Sinhala', population: 21.44},
    {name: 'USA', language: 'American English', population: 327.2},
    {name: 'India', language: 'Hindi', population: 1355.80},
    {name: 'UK', language: 'UK English', population: 66.44},
  ];

  allCountries.forEach((country) => {
     console.log(country.name);
  });

Result – 

This makes working with arrays where you need to loop over them easier since you don’t have to write out the clunky long for loop syntax as you’d normally have to.


20) some()

sum() checks any element in the array return a true for the condition inside the function. If a single item returns true, it’s going to return true for the entire thing.

For example,  we can check if some of the items in this array have a population of less than 50 million.

  const allCountries = [
    {name: 'Sweden', language: 'Swedish', population: 10.12},
    {name: 'Sri Lanka', language: 'Sinhala', population: 21.44},
    {name: 'USA', language: 'American English', population: 327.2},
    {name: 'India', language: 'Hindi', population: 1355.80},
    {name: 'UK', language: 'UK English', population: 66.44},
  ];

const isLessPopulCountryInclude =  allCountries.some((country) => {
     return country.population <=50;
  });
  
  console.log(isLessPopulCountryInclude);
Syntax - array.some(function(currentValue, index, arr), thisValue)

Result – 


21) Every()

every()method check if all values in the array meet the condition true for provided function and if it finds any element returns a false value and then every() method will also return false.

Let say, if we want to check all the population in each country has more than 20 million, Every() method will be a better option.

const allCountries = [
    {name: 'Sweden', language: 'Swedish', population: 110.12},
    {name: 'Sri Lanka', language: 'Sinhala', population: 21.44},
    {name: 'USA', language: 'American English', population: 327.2},
    {name: 'India', language: 'Hindi', population: 1355.80},
    {name: 'UK', language: 'UK English', population: 66.44},
  ];

const totalPopulationOfEveryCountries = allCountries.every((country) => {
     return country.population > 10;
  });
  
  console.log(totalPopulationOfEveryCountries);

Result – 

It does not check the remaining value. It will return true, if no false occur for each element.

What do you think about these javascript array methods? Let us know in the comment section below. Happy coding! 🙂

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *

Related Articles

Cool Gadgets on Amazon 2019 | Cool Amazon Products

Cool Gadgets on Amazon 2019 | Cool Amazon ProductsG, 0 Comments Today’s, topic about Cool Gadgets on Amazon 2019. Now, let's go and know about those gadgets in more deep. 01. The orange screwThis is one of the most clever and versatile tools you'll ever...

Is Interstellar Travel Impossible? | Interstellar Travel

Is Interstellar Travel Impossible? | Interstellar TravelG, 0 Comments Today's, topic about Interstellar Travel Impossible. Let's go into deep and understand the scientific facts related to this topic. Simply, Is interstellar travel doomed to remain in the...

Smart Retail Technology in IoT – Smart Retail Stores

Smart Retail Technology in IoT – Smart Retail StoresG, 0 Comments Today's topic is about "How IOT Gives Rise to Smart Retail Technology". Simply, I want you to picture your kitchen at home. If you're like most people you can trace many of your...

Stay Up to Date With The Latest News & Updates

Join Our Newsletter

Follow Us