logo

  • Hỏi Đáp
  • Kiến Thức
  • Sức Khỏe
  • Tử Vi
  • Công Nghệ
No Result
View All Result
logo
No Result
View All Result
Trang chủ filter an array of objects in javascript

FILTER AN ARRAY OF OBJECTS IN JAVASCRIPT

by Admin _ August 04, 2022

Summary: in this tutorial, you will learn how to use the JavaScript Array filter() method to filter elements in an array.

Bạn đang xem: Filter an array of objects in javascript

Introduction khổng lồ JavaScript array filter() method

One of the most common tasks when working with an array is to lớn create a new array that contains a subset of elements of the original array.

Suppose you have an array of thành phố objects where each object contains two properties: name and population.


let cities = < name: "Los Angeles", population: 3792621, name: "New York", population: 8175133, name: "Chicago", population: 2695598, name: "Houston", population: 2099451, name: "Philadelphia", population: 1526006>;
Code language: JavaScript (javascript)To find the city whose population is greater than 3 million, you typically loop over the array elements using a for loop & test if the value of the population property satisfies the condition, lượt thích this:


let bigCities = <>;for (let i = 0; i if (cities.population > 3000000) bigCities.push(cities); }console.log(bigCities);
Code language: JavaScript (javascript)JavaScript Array provides the filter() method that allows you to bởi vì this task in a shorter and cleaner way.

The following example returns the same result as the example above:


let bigCities = cities.filter(function (e) return e.population > 3000000;);console.log(bigCities);
Code language: JavaScript (javascript)In this example, we hotline the filter() method of the cities array object and pass a function that tests each element.

Inside the function, we check if the population of each đô thị in the array is greater than 3 million. If it is the case, the function returns true or false otherwise. 

The filter() method includes the only elements in the result array if they satisfy the demo in the callback function.

Starting with ES6, you can use the arrow function khổng lồ make it more concise:


let bigCities = cities.filter(city => city.population > 3000000);console.log(bigCities);
Code language: JavaScript (javascript)

JavaScript Array filter() method in detail

The following illustrates the syntax of the filter() method:


arrayObject.filter(callback, contextObject);
Code language: CSS (css)The filter() method creates a new array with all the elements that pass the thử nghiệm implemented by the callback() function.

Internally, the filter() method iterates over each element of the array and passes each element to lớn the callback function. If the callback function returns true, it includes the element in the return array.

The filter() method accepts two named arguments: a callbackfunction & an optional object.

Like other iterative methods of the Array object such as every(), some(), map() & forEach(), the callbackfunction has the following form:


function callback(currentElement, index, array) // ...
Code language: JavaScript (javascript)The callback function takes three arguments:

The currentElement argument is the current elementin the array that is being processed by the callback function.The index of the currentElement that is being processed by the callback function.The array object being traversed.

Xem thêm: Hướng Dẫn Đăng Ký Tải Game Au Mix, ‎Au Mix On The App Store

The index và array arguments are optional.

The contexObject argument of the filter() method is optional. If you pass the this value, you can reference it by using this từ khóa inside the callback function.

It is important to lưu ý that the filter() method does not change the original array.

More JavaScript Array filter() method examples

Because the filter() method returns a new array, you can chain the result with other array methods such as sort() & map().

For example, the following illustrates how lớn chain the three methods: filter(),sort(), & map():


cities .filter(city => city.population 3000000) .sort((c1, c2) => c1.population - c2.population) .map(city => console.log(city.name + ":" + city.population));
Code language: JavaScript (javascript)Output:


Philadelphia:1526006Houston:2099451Chicago:2695598
Code language: CSS (css)How it works.

First, filter the cities whose populations are less than 3 million using the filter() method.Second, sort the resulting cities by the populations in descending order using the sort() method.Third, đầu ra array element lớn the console using the map() method.

The following example illustrates the use of the contextObject argument that specifies an object which can be referenced in the callback() function using the this keyword


function isInRange(value) if (typeof value !== "number") return false; return value >= this.lower && value this.upper;let data = <10, 20, "30", 1, 5, "JavaScript filter", undefined, "example">;let range = lower: 1, upper: 10;let numberInRange = data.filter(isInRange, range);console.log(numberInRange); // <10, 1, 5>
Code language: JavaScript (javascript)Output:


< 10, 1, 5 >
Code language: JSON / JSON with Comments (json)How it works.

First, define the isInRange() function that checks if its argument is a number and in the range specified by the lower và upper properties of an object.Then, define the range object with two properties lower and upper.After that, điện thoại tư vấn the filter() methods of the data array & pass in the isInRange() function và the range object. Because we pass in the range object, inside the isInRange() function, the this từ khóa references khổng lồ the range object.Finally, show the result array in the console.

In this tutorial, you have learned how to lớn use the JavaScript Array filter() method lớn filter elements in an array based on a kiểm tra provided by a callback function.


Was this tutorial helpful ?

Yes No

*

Previously
JavaScript Array map: Transforming Elements
Up Next
JavaScript Array reduce & reduceRight: Reducing an Array Into a Value
*

search for:

Properties


Adding / Removing Elements


Finding Elements


High-order Methods


Manipulating Arrays


Creating Arrays


Flattenning Arrays


Arrays lớn Strings


Advanced Operations


Accessing Elements


Multidimensional Arrays


Arrays & Data Structures


About JavaScript Tutorial


The JavaScript Tutorial trang web helps you learn JavaScript programming from scratch quickly & effectively.

References


Latest Tutorials


Site Links


Share Tweet Linkedin Pinterest
Previous Post

Urlsearchparams

Next Post

Javascript array push key value code example

CÙNG CHUYÊN MỤC

lấy giá trị của option trong javascript

Lấy giá trị của option trong javascript

28/03/2021
lấy giá trị từ input trong javascript

Lấy giá trị từ input trong javascript

28/04/2021
download javascript for windows 10

Download javascript for windows 10

28/04/2021
nhập dữ liệu từ bàn phím trong javascript

Nhập dữ liệu từ bàn phím trong javascript

28/04/2021
how to select a random element from array in javascript

How to select a random element from array in javascript

08/08/2022
độ ưu tiên toán tử trong javascript

Độ ưu tiên toán tử trong javascript

07/08/2022
tìm 1 ký tự trong chuỗi javascript

Tìm 1 ký tự trong chuỗi javascript

06/08/2022
lấy dữ liệu từ textarea javascript

Lấy dữ liệu từ textarea javascript

05/08/2022

Newsletter

The most important automotive news and events of the day

We won't spam you. Pinky swear.

Chuyên Mục

  • Hỏi Đáp
  • Kiến Thức
  • Sức Khỏe
  • Tử Vi
  • Công Nghệ

News Post

  • Phần mềm erp là gì

About

Chúng tôi tạo ra trang web nhằm mục đích mang lại kiến thức bổ ích cho cộng đồng, các bài viết được sưu tầm từ nhiều nguồn trên internet giúp mang lại kiến thức khách quan dành cho bạn

©2022 darkedeneurope.com - Website WordPress vì mục đích cộng đồng

Liên Hệ - Giới Thiệu - Nội Quy - Bảo Mật

No Result
View All Result
  • Trang chủ
  • Chuyên mục
    • Hỏi Đáp
    • Kiến Thức
    • Sức Khỏe
    • Tử Vi
    • Công Nghệ
  • Lưu trữ
  • Liên hệ

© 2022 darkedeneurope.com - Website WordPress vì mục đích cộng đồng.