简体   繁体   English

返回包含条件的数组的长度

[英]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},])

How to return the length of an array consisting of person age more than 22 years old which should be 2.如何返回由年龄超过 22 岁的人组成的数组的长度,该数组的长度应为 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM