如何遍历人员数组处理年龄并筛选25岁以上人员?
Solution for Processing and Filtering People by Age
Got it, let's break this down step by step so you can build out your solution smoothly:
Step 1: Process the age field for each person
First, we need to normalize the age value for every entry in the array:
- If
ageis an array, calculate the sum of all its elements - If
ageis already a number, keep it as-is
We’ll use Array.map() here because it creates a new array with modified values without messing with the original data (a clean practice for avoiding unintended side effects).
Step 2: Filter people with age over 25
Once we have the processed array with summed ages, we’ll use Array.filter() to keep only those entries where the updated age is greater than 25.
Complete Code Implementation
const ListOfPeople = [ { name: 'Mia', age: [10, 5, 5] }, { name: 'Steve', age: 30 }, { name: 'Emma', age: [2, 12, 16, 10] } ]; const filterPeople = (peopleList) => { // Step 1: Transform each person's age const processedPeople = peopleList.map(person => { let calculatedAge; // Check if age is an array if (Array.isArray(person.age)) { // Sum array elements using reduce (starts at 0 to handle empty arrays safely) calculatedAge = person.age.reduce((total, current) => total + current, 0); } else { // Age is already a number, use it directly calculatedAge = person.age; } // Return a new object with updated age (avoids mutating original data) return { ...person, age: calculatedAge }; }); // Step 2: Filter for people over 25 return processedPeople.filter(person => person.age > 25); }; // Test the function console.log(filterPeople(ListOfPeople)); // Output: [{ name: 'Steve', age: 30 }, { name: 'Emma', age: 40 }]
Quick Notes on Key Parts
Array.isArray(): This is how we reliably check ifageis an array (critical for handling the mixed data types in your input).Array.reduce(): Perfect for summing array values—we start with 0 as the initial total to avoid issues if an age array is empty.- Spread operator (
...person): Creates a copy of the original person object instead of modifying it directly, keeping our function "pure" and predictable. - Concise Chained Version: If you prefer shorter code, you can chain
map()andfilter()together:const filterPeople = (peopleList) => peopleList .map(person => ({ ...person, age: Array.isArray(person.age) ? person.age.reduce((a, b) => a + b, 0) : person.age })) .filter(person => person.age > 25);
内容的提问来源于stack exchange,提问作者user8227859
相关产品推荐
相关产品推荐

