SoFunction
Updated on 2025-04-06

How to use js to find elements that match criteria in an array

Several ways to find qualified elements in an array

1. Use for loop to search

let arr = [
  {name: 'zhangsan', age: 18},
  {name: 'lisi', age: 17},
  {name: 'xiaoming', age: 18},
],
result = []
for (let item of arr){
  if( === 18){
    (item);
  }
}
(result);// [{name: 'zhangsan', age: 18},{name: 'xiaoming', age: 18}]

2. filter() method

Notice:

The filter() method creates a new array, and the elements in the new array are checked for all elements in the specified array that meet the criteria.

filter() does not detect empty arrays.

filter() does not change the original array.

let arr = [
  {name: 'zhangsan', age: 18},
  {name: 'lisi', age: 17},
  {name: 'xiaoming', age: 18},
];
let result = (item=> === 18)
(result);// [{name: 'zhangsan', age: 18},{name: 'xiaoming', age: 18}]

3. Find() method

Notice:

The find() method only returns the first element in the array that meets the condition, not all elements

When an element in the array returns true when the condition returns, find() returns an element that meets the condition, and the subsequent value will no longer call the execution function.

If no element that meets the criteria returns undefined

find() function will not execute for empty arrays.

find() does not change the original value of the array.

let arr = [
  {name: 'zhangsan', age: 18},
  {name: 'lisi', age: 17},
  {name: 'xiaoming', age: 18},
];
let result = (item=> === 18)
(result);// {name: 'zhangsan', age: 18}

Attachment: JavaScript finds the value in an array that meets a certain condition and saves the value that meets the condition into a new array

1. Using the find function and the es6 arrow function, the following method takes the first element in the array that meets the conditions;

var newArray  = {};//New objectvar array = [
 {name:'aiai',age:18},
 {name:'sisi',age:18},
 {name:'lulu',age:18},
 {name:'sisi',age:19}
]; 
//Find the matching values ​​and save them in a new arraynewArrar = ((item) => {
   if( === 'sisi'){
     return item
   }
 })
//At this time newArray = {name:'sisi',age:18}

2. Find all elements that meet the criteria

var newArray  = [];//New arrayvar j = 0;
var array = [
 {name:'aiai',age:18},
 {name:'sisi',age:18},
 {name:'lulu',age:18},
 {name:'sisi',age:19}
]; //Target array 
//Find the matching values ​​and save them in a new arrayfor(let i in array){
 if(array[i].name == 'sisi'){
  newArray[j++] = array[i]
 }
}
//at this time newArray = [{name:'sisi',age:18},{name:'sisi',age:19}]

Summarize

This is the article about how to use js to find elements that meet the conditions in an array. For more related js to find elements that meet the conditions in an array, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!