-6
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.

Eddie
  • 26,593
  • 6
  • 36
  • 58
zikpo
  • 1
  • 2
    The posted question does not appear to include [any attempt](https://idownvotedbecau.se/noattempt/) at all to solve the problem. StackOverflow expects you to [try to solve your own problem first](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users), as your attempts help us to better understand what you want. Please edit the question to show what you've tried, so as to illustrate a specific problem you're having in a [MCVE]. For more information, please see [ask] and take the [tour]. – CertainPerformance Oct 03 '18 at 03:51
  • 1
    Possible duplicate of [Javascript: How to filter object array based on attributes?](https://stackoverflow.com/questions/2722159/javascript-how-to-filter-object-array-based-on-attributes) – Tyler Roper Oct 03 '18 at 03:52
  • 1
    You can use `.filter()` to get all objects with greater than 22 age. Use `.length` to get the number of objects. – Eddie Oct 03 '18 at 04:06
  • use `filter` like `arr.filter(function(ar){ return ar.age > 22; }); ` – Shiv Kumar Baghel Oct 03 '18 at 04:08

3 Answers3

0

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},]));
protoproto
  • 2,081
  • 1
  • 13
  • 13
0

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,

jonathangersam
  • 1,137
  • 7
  • 14
0

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