DEV Community

Cover image for Useful JavaScript array methods - Part 2
Phyllis
Phyllis

Posted on

Useful JavaScript array methods - Part 2

JavaScript provides a bunch of helpful methods for working with arrays. This article, which is a follow up to my previous post, will take you through some of the commonly used array callback methods. Again, I will group these methods by the purpose of data transformation.

We will use ES6 arrow functions in the examples below. If you haven't used them and would like to find out more about it, you may find this article helpful.

Table of content

  1. Iterate - forEach
  2. Transform - map
  3. Filter - filter
  4. Query - every, some

Iterate - forEach

iterate

This method is used for running a function for each array element. You can also get the current index of each element if you need it.

Examples 1 & 2: extract values from an array of objects

const restaurants =[{
  name: 'Tasca da Avenida',
  cuisine:'Mediterranean',
  rating: 4.3
 },
 {
  name:'Decor & Salteado',
  cuisine:'European',
  rating: 4.6
 },
 {
  name:'Carnes do Convento',
  cuisine:'Mediterranean',
  rating: 4.8
 }
]

//printing all restaurants' names
restaurants.forEach((r) => {
  console.log(r.name);
});

// Tasca da Avenida
// Decor & Salteado 
// Carnes do Convento

//printing all restaurants' name with their indices
restaurants.forEach((r, index) => {
  console.log(`${index}: ${r.name}`);
});

// 0: Tasca da Avenida
// 1: Decor & Salteado
// 2: Carnes do Convento

Enter fullscreen mode Exit fullscreen mode

Example 3: multiply each element in the array by 3

const numbers = [2,4,6,8,10];
numbers.forEach((num) => {
  console.log(num * 3);
});

numbers
// 6
// 12 
// 18
// 24
// 30

Enter fullscreen mode Exit fullscreen mode

Transform - map

transform

This method iterates over each element of an array and transforms them into new elements. The original array will not be changed, but a new array, consists of these new elements, will be created.

When to use map and forEach?

map: it returns values after manipulating data of the original array and those values are saved in a new array which can be used later.

forEach: There is no return value from the method. It only manipulates the data of the original array without creating a new array.

Therefore if we simply want to do something with the array without creating a new array, we can use .forEach(). But if we want to capture the result of data manipulation in a new array, we should go for .map().

Example 1: Transform each element in an array and save them in a new array

const tea = ['cranberry', 'breakfast', 'earl grey', 'strawberry'];

// turn the tea names into uppercase characters and save them in a new variable uppercased
const uppercased = tea.map((t) => {
  return t.toUpperCase();
});

console.log(uppercased);

//["CRANBERRY", "BREAKFAST", "EARL GREY", "STRAWBERRY"]

Enter fullscreen mode Exit fullscreen mode

Example 2: return an object which includes the numbers in the array and whether each of them can be divided by 5

const numbers = [ 5, 3, 7, 10, 15];

const fiveMultiples = numbers.map((num) => {
  return {
    value: num,
    dividedByFive: num % 5 === 0
  }
});

fiveMultiples
//0: {value: 5, dividedByFive: true}
//1: {value: 3, dividedByFive: false}
//2: {value: 7, dividedByFive: false}
//3: {value: 10, dividedByFive: true}
//4: {value: 15, dividedByFive: true}

Enter fullscreen mode Exit fullscreen mode

Filter -filter

filter

.filter() returns a new array with elements which fulfils a condition specified by you. It works like this:

  1. It loops over each element of an existing array.
  2. If the element fulfils a testing function specified by you, the result will be true and that element will be included in the new array.
  3. If the element does not pass the testing function, the result will be false and that element will be excluded from the new array.
  4. The original array will not be changed.

Example 1: find out numbers which are greater than 100 and save them in a new array bigNumbers.

const numbers = [10, 50, 102, 789, 5, 101];
const bigNumbers = numbers.filter(num => num > 100);
bigNumbers
// [102, 789, 101]
Enter fullscreen mode Exit fullscreen mode

Example 2: find out Mediterranean restaurants and save them in a new array called seacrhResult.

const restaurants = [{
    name: 'Tasca da Avenida',
    cuisine: ['Mediterranean', 'Seafood'],
    rating: 4.3
  },
  {
    name: 'Decor & Salteado',
    cuisine: ['European', 'International'],
    rating: 4.6
  },
  {
    name: 'Carnes do Convento',
    cuisine: ['Mediterranean', 'Steakhouse'],
    rating: 4.8
  }
]

const searchResult = restaurants.filter((r) => {
  return r.cuisine.includes("Mediterranean");
})

searchResult

//{name: "Tasca da Avenida", cuisine: Array(2), rating: 4.3}
//{name: "Carnes do Convento", cuisine: Array(2), rating: 4.8}

Enter fullscreen mode Exit fullscreen mode

Query - every, some

query

Every

.every() is used when we want to see if all the elements in an array passes a condition defined by us. It returns a boolean value. In other words, if all the elements passes the condition, it will return true. Otherwise, it will return false.

Example: check if all the restaurants above have a rating of at least 4.5.

const allGoodRestaurants = restaurants.every(restaurant => restaurant.rating >= 4.5);

allGoodRestaurants
//false
Enter fullscreen mode Exit fullscreen mode

Some

.some() is similar to .every(). The only difference is, instead of checking if all array elements fulfil the condition, .some() only checks if at least one array element passes the test function.

In other words, if one or more elements passes the test function, it will return true. If none of the elements fulfils the condition, it will return false.

Example: check if at least one of the restaurants above has a rating of at least 4.5.

const someGoodRestaurants = restaurants.some(restaurant => restaurant.rating >= 4.5);

someGoodRestaurants
//true
Enter fullscreen mode Exit fullscreen mode

Thanks for reading! This article is far from comprehensive. There are still some methods which have not been covered. If you want to find out more about JS array methods, you can check out the docs on MDN. It's really good reference for learning and understanding how they work.

Buy Me A Coffee

Top comments (5)

Collapse
 
favouritejome profile image
Favourite Jome

Thanks for sharing, simply explained

Collapse
 
phyllis_yym profile image
Phyllis

You’re welcome ! Glad you found it easy to understand

Collapse
 
timhuang profile image
Timothy Huang

Very useful, thank you!

Collapse
 
phyllis_yym profile image
Phyllis

You're welcome!

Collapse
 
tracycss profile image
Jane Tracy πŸ‘©πŸ½β€πŸ’»

Thanks for sharing. The examination is simple and clear. πŸ₯°πŸ’―🌟