【问题标题】:return the length of an array with the condition in it返回包含条件的数组的长度
【发布时间】:2018-10-03 03:50:22
【问题描述】:
function(people){

}
people([{name: 'John', age: 22},{name: 'paul', age: 23},{name: 'mathew', age: 24},])

如何返回由 22 岁以上的人组成的数组的长度,应该是 2。

【问题讨论】:

标签: javascript arrays


【解决方案1】:

你可以使用数组reduce来计数:

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

【讨论】:

    【解决方案2】:

    以下是您问题的函数式编程方法:

    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')

    希望这会有所帮助。 干杯,

    【讨论】:

      【解决方案3】:

      请尝试以下操作:

      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);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-12-10
        • 1970-01-01
        • 2013-12-10
        • 2014-02-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-07-23
        相关资源
        最近更新 更多