Reputation: 351
I want to get the length of an array that match the value specified by the condition.
var school = {
student : {
name: Json,
class: 0,
type: male,
average: B+
},
student : {
name: Afrado,
class: 0,
type: male,
average: C+
},
student : {
name: Emily,
class: 1,
type: female,
average: A+
}
};
I'd like to know the lengh of class "0"
but I don't know how to resolve this case?
In this case I can get the length of "2" for my results.
Have a nice day~ :)
Upvotes: 0
Views: 57
Reputation: 2081
you can also use this way:
var school = [
{
name: "Json",
class: 0,
type: "male",
average: "B+"
},
{
name: "Afrado",
class: 0,
type: "male",
average: "C+"
},
{
name: "Emily",
class: "1",
type: "female",
average: "A+"
}
];
function search(className, myArray){
var countClass = 0;
for (var i=0; i < myArray.length; i++) {
if (myArray[i].class === className) {
countClass++;
}
}
return countClass;
}
function searchForeach(className, myArray){
var countClass = 0;
myArray.forEach((item) => {
if (item.class === className) {
countClass++;
}
});
return countClass;
}
function searchFind(className, myArray){
var countClass = 0;
myArray.find((item, index) => {
if (item.class === className) {
countClass++;
}
});
return countClass;
}
console.log(search(0, school));
console.log(searchForeach("1", school));
console.log(searchFind(0, school));
second way use find:
Upvotes: 0
Reputation: 872
You can use the reduce function to avoid creating a temporary array with filter.
console.log(school.reduce((count, student) => student.class === 0 ? ++count : count, 0));
Upvotes: 0
Reputation: 346
Your array is not structured properly, what you need to do is to filter
and get the length
of the filtered items.
var school = [
{
name: "Json",
class: 0,
type: "male",
average: "B+"
},
{
name: "Afrado",
class: 0,
type: "male",
average: "C+"
},
{
name: "Emily",
class: "1",
type: "female",
average: "A+"
}
];
console.log(school.filter(student => student.class === 0).length);
Upvotes: 2