Javascript filter returning two individual objects rather than array

Viewed 29

Hi I am using filter to filter through an array and get the length of filtered values returned. However it is returning individual objects rather than an array, so I am unable to use .length on these.

Code I'm using to filter:

const pupils = kids.inputs.filter(k => k.attendsSchool);

const number = pupils.length
const kids = {
  areaId: "0x2132425",
  inputs: [
    {
      name: "anne",
      gender: "girl",
      age: 6,
      attendsSchool: true,
      _id: "632c78ddae73c67bf67ff2d7",
    },
    {
      name: "bob",
      gender: "boy",
      age: 7,
      attendsSchool: true,
      _id: "632c78ddae73c67bf67ff2d8",
    },
    {
      name: "charlie",
      gender: "boy",
      age: 2,
      attendsSchool: false,
      _id: "632c78ddae73c67bf67ff2d9",
    },
  ]
}

What is getting returned to pupils:

0: {
"name": "anne",
"gender": "girl",
"age": 6,
"attendsSchool": true,
"_id": "632c78ddae73c67bf67ff2d7",
}
1: {
"name": "bob",
"gender": "boy",
"age : 7,
"attendsSchool": true,
"_id": "632c78ddae73c67bf67ff2d8",
}

Is there away to get array returned or measure number of items, they are also not in the one object as I can't get length based on object keys

1 Answers

This is working for me as well.

console.log(number); returns 2.
console.log(pupils[0]); returns the whole object for "anne".

This is using the exact code you have written in your question: Codepen snapshot

Related