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

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

内容简介: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.


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

查看所有标签

猜你喜欢:

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

离散数学及其应用(原书第7版)

离散数学及其应用(原书第7版)

Kenneth H. Rosen / 徐六通、杨娟、吴斌 / 机械工业出版社 / 2015-1-1 / 129

《计算机科学丛书:离散数学及其应用(原书第7版)》是介绍离散数学理论和方法的经典教材,已经成为采用率最高的离散数学教材,被美国众多名校用作教材,获得了极大的成功。中文版也已被国内大学广泛采用为教材。作者参考使用教师和学生的反馈,并结合自身对教育的洞察,对第7版做了大量的改进,使其成为更有效的教学工具。《计算机科学丛书:离散数学及其应用(原书第7版)》可作为1至2个学期的离散数学课入门教材,适用于数......一起来看看 《离散数学及其应用(原书第7版)》 这本书的介绍吧!

HTML 编码/解码
HTML 编码/解码

HTML 编码/解码

MD5 加密
MD5 加密

MD5 加密工具

XML、JSON 在线转换
XML、JSON 在线转换

在线XML、JSON转换工具