JavaScript find() and filter() Array Iteration Methods Made Easy

栏目: IT技术 · 发布时间: 5年前

内容简介:With the ever-improving ecosystem of JavaScript, the ES6 version of JavaScript unwraps theUsing these methods reduces the use of for, while, do-while loops and the likes which have more verbose syntax relative to the array iteration methods.While this arti
JavaScript find() and filter() Array Iteration Methods Made Easy

JavaScript find() and filter() Array Iteration Methods Made Easy

With the ever-improving ecosystem of JavaScript, the ES6 version of JavaScript unwraps the array iteration methods that help its developers write clean and readable code. Some of these iteration methods are immutable, which means they do not change the original array.

Using these methods reduces the use of for, while, do-while loops and the likes which have more verbose syntax relative to the array iteration methods.

While this article will be more focused on making you understand these two array iteration methods, it will also create a fun, interesting and easy learning experience to its readers.

Let’s have fun as we get started.

How to Get the Most Out of This Article

  • If you are conversant with these iteration methods already, this article will serve as a great reference piece to you in the future.
  • If you are new to the iteration methods in JavaScript, I urge you to get your hands on your keyboard and type along as this will help retain the syntax associated with these methods to your memory.
  • Ensure that all doubts and misunderstandings are cleared by leaving your questions and comments for this article in the comment section.

What is an Array

According to MDN: An array is an ordered collection of data (either primitive or object depending upon the language). Arrays are used to store multiple values in a single variable. This is compared to a variable that can store only one value.

Each item in an array has a number attached to it, called a numeric index, that allows you to access it. In JavaScript, arrays start at index zero and can be manipulated with various methods.

To simplify this definition, let’s visualize an array as a container that stores Different kinds of elements in an orderly manner.

As earlier said, we will have lots of fun while learning. Since I am a football fanatic, we will analyze some top football stars in the world of football.

Common guys, let’s get to the pitch…

// Players array
let myFavouritePlayers = [
   {
      'id': 001,
      'first_name': 'Christiano',
      'last_name': 'Ronaldo',
      'gender': 'M',
      'Nationality': 'Portugal',
      'Height': '71ft',
      'age': 32,
      'position': 'striker',
      'career_goals': 648,
      'trophies': 37,
      'current_team': 'Juventus',
      'teams-played': ['sporting_lisbon', 'Manchester_united', 'Real_madrid', 'Juventus']
   },
   {
      'id': 002,
      'first_name': 'Lionel',
      'last_name': 'Messi',
      'gender': 'M',
      'Nationality': 'Argentina',
      'Height': '61ft',
      'age': 31,
      'position': 'striker',
      'career_goals': 748,
      'trophies': 30,
      'current_team': 'Barcelona',
      'teams-played': ['Barcelona']
   },
   {
      'id': 003,
      'first_name': 'Paulo',
      'last_name': 'Dybala',
      'gender': 'M',
      'Nationality': 'Argentina',
      'Height': '64ft',
      'age': 32,
      'position': 'Midfielder',
      'career_goals': 318,
      'trophies': 15,
      'current_team': 'Juventus',
      'teams-played': ['Palermo','Juventus']
   },
   {
      'id': 004,
      'first_name': 'Harry',
      'last_name': 'Kane',
      'gender': 'M',
      'Nationality': 'England',
      'Height': '78ft',
      'age': 22,
      'position': 'striker',
      'career_goals': 328,
      'trophies': 3,
      'current_team': 'Totenham_hotspur',
      'teams-played': ['Totenham_hotspur']
   },
   {
      'id': 005,
      'first_name': 'Ryaid',
      'last_name': 'Mahrez',
      'gender': 'M',
      'Nationality': 'Algeria',
      'Height': '68ft',
      'age': 24,
      'position': 'striker',
      'career_goals': 228,
      'trophies': 4,
      'current_team': 'Manchester_city',
      'teams-played': ['Liceister_city', 'Manchester_city']
   },
   {
      'id': 006,
      'first_name': 'Kun',
      'last_name': 'Aguero',
      'gender': 'M',
      'Nationality': 'Argentina',
      'Height': '64ft',
      'age': 22,
      'position': 'center_forward',
      'career_goals': 428,
      'trophies': 10,
      'current_team': 'Manchester_city',
      'teams-played': ['Athletico_madrid', 'Manchester_city']
   },
];

Brace-up, let’s go have some fun learning these iteration methods.

Array.prototype.find() iteration method

The ES6 find method looks through each element in an array in search of the first item that passes the conditions in its callback function and when found, that element is returned else a value of undefined is returned. This look-up is carried out only once for an array.

Syntax

const foundItem = myArray.find(callbackFunction);

Callback function

Syntax

callback(element, index, array)

This is the function that houses the conditions to be executed over each element of the array. The first item that meets the conditions is returned.

The callback function receives 3 parameters which include:

  • array: the array that is currently being processed. It is optional.
  • index: the index of the current item. It is optional.
  • element: this is the element currently being executed. It is usually required.

The array.find() method in action

Let’s implement a feature to find the hitman goal scorer in the world.

Diego Maradona happens to be the highest goalscorer of all time with carrer_goals of 730.

Our hitman goal scorer is any player who breaks Maradona’s goalscoring record by scoring more goals than him.

const Maradona = 730;
const hitmanGoalscorer = myFavouritePlayers.find((player) => {
   return (player.career_goals > Maradona);
});
console.log(hitmanGoalscorer);

Results

{
      id: 002,
      first_name: 'Lionel',
      'last_name': 'Messi',
      gender: 'M',
      Nationality: 'Argentina',
      Height: '61ft',
      age: 31,
      position: 'striker',
      career_goals: 748,
      trophies: 30,
      current_team: 'Barcelona',
      teams-played: ['Barcelona']
   }

Index

The index parameter of the callback function is applicable in getting an element in an array at a specific index.

Let’s illustrate with the code snippet below:

// find array item with index of 2
 
const playerAtIndex = myFavouritePlayers.find((player, index)=> index === 2)
 
// display array item found
 
console.log(playerAtIndex)
// milk

In this snippet, the find() method is implemented with the ES6 arrow function.

Array.prototype.filter() iteration method

The ES6 filter() method creates a new array with all elements that meet the conditions implemented by the callback function. An empty array will be returned if no elements meet the conditions

Syntax

const filteredItem = myArray.filter(callbackFunction);

Callback function

Syntax

callback(element, index, array)

This is the function that houses the conditions to be executed over each element of the array thereby returning a new array containing the items that passed the conditions.

The callback function receives 3 parameters which include:

  • array: the array that is currently being processed. It is optional.
  • index: the index of the current item. It is optional.
  • element: this is the element currently being executed. It is usually required.

The array.filter() method in action

Let’s implement a feature to filter all the midfielders in the list of my favorite players.

// filter myFavouritePlayers array //for strikers
 
const midfielders = myFavouritePlayers.filter((player)=> player.position === 'Midfielder');
 
// display all strikers found
 
console.log(midfielders);

Results

[Object 
{  
      id: 003,
      first_name: 'Paulo',
      last_name: 'Dybala', 
      gender: 'M',Nationality: 'Argentina',   
      Height: "64ft",
      age: 32, 
      career_goals: 318, 
      current_team: "Juventus", 
      teams-played: ['Palermo', 'Juventus']  
},
{
      id: 005,
      first_name: 'Ryaid',
      last_name: 'Mahrez',
      gender: 'M',
      Nationality: 'Algeria',
      Height: '68ft',
      age: 24,
      position: 'striker',
      career_goals: 228,
      trophies: 4,
      current_team: 'Manchester_city',
      teams-played: ['Liceister_city', 'Manchester_city']
   }
]

Differences between the find iteration method and filter iteration method

Returned value: the filter method returns a new array containing the items that met the conditions stated in the callback function while the find method returns just a single item from the array.

Conclusion

Consequently, the array.find method is a great method for searching for a certain item in an array in JavaScript. But if you are considering the search for items more than one, the JavaScript array.filter method is just what you need.

I hope you had lots of fun learning these iteration methods. For any question or comment, hit the comment section.


以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,也希望大家多多支持 码农网

查看所有标签

猜你喜欢:

本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们

众包

众包

杰夫·豪 / 牛文静 / 中信出版社 / 2009-6 / 36.00元

本书是继《长尾理论》之后的重要商业书籍。本书回答了《长尾理论》遗留的一大悬念。在长尾中作者详细阐述了长尾之所以成为可能的一个基础,但是没有详细解读,本书就是对这一悬念的详细回答,是《长尾理论》作者强力推荐的图书,在国际上引起了不小的轰动,“众包”这一概念也成为一个标准术语被商界广泛重视。本书大致分为三个部分,介绍众包的现在、过去和未来,解释了它的缘起、普遍性、力量以及商业上的适用性,通俗易懂,精彩......一起来看看 《众包》 这本书的介绍吧!

CSS 压缩/解压工具
CSS 压缩/解压工具

在线压缩/解压 CSS 代码

html转js在线工具
html转js在线工具

html转js在线工具

UNIX 时间戳转换
UNIX 时间戳转换

UNIX 时间戳转换