function(people){
}
people([{name: 'John', age: 22},{name: 'paul', age: 23},{name: 'mathew', age: 24},])
How to return the length of an array consisting of person age more than 22 years old which should be 2.
You can use array reduce to count:
function people(array){ return array.reduce((total, current)=>{ if(current.age>22) total = total +1; return total; },0); } console.log(people([{name: 'John', age: 22},{name: 'paul', age: 23},{name: 'mathew', age: 24},]));
Below is the functional programming approach to your question:
const persons = [ {name: 'John', age: 22}, {name: 'paul', age: 23}, {name: 'mathew', age: 24} ] const over22 = persons.filter(person => person.age > 22) console.log('there are', over22.length, 'people aged over 22')
Hope this helps. Cheers,
Please try following :
function find_length(checkField, valueField, myArray) {
for (var i = 0; i < myArray.length; i++) {
if (myArray[i][checkField] == valueField) {
return Object.keys(myArray[i]).length;
}
}
}
var myList = [{name: 'John', age: 22}, {name: 'paul', age: 23}, {name: 'mathew', age: 24},];
var ageObjLength = find_length('age', '22', myList );
alert("Length is " + ageObjLength);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.