[英]return the length of an array with the condition in it
function(people){
}
people([{name: 'John', age: 22},{name: 'paul', age: 23},{name: 'mathew', age: 24},])
如何返回由年齡超過 22 歲的人組成的數組的長度,該數組的長度應為 2。
您可以使用數組減少來計數:
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},]));
以下是針對您的問題的函數式編程方法:
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')
希望這可以幫助。 干杯,
請嘗試以下操作:
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);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.