0

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~ :)

asked Dec 5, 2019 at 5:35

3 Answers 3

2

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);
answered Dec 5, 2019 at 5:43

Comments

0

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));
answered Dec 5, 2019 at 5:54

Comments

0

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:

answered Dec 5, 2019 at 6:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.