I have the following array with objects, and the object consists of an array. I would like to return the total length of the array "species".
let fish = [
{
"name": "salmon",
"species": [
{
"name": "atlantic salmon",
"gender": "male"
},
{
"name": "sockeye salmon",
"gender": "female"
},
],
},
{
"name": "carp",
"species": [
{
"name": "grass carp",
"gender": "male"
},
{
"name": "common carp",
"gender": "female"
},
],
},
]
I would like to get back a result of 4 from this but I'm not too sure how. Any suggestions? Thanks!
Try this line. It works fine.
let fish = [
{
"name": "salmon",
"species": [
{
"name": "atlantic salmon",
"gender": "male"
},
{
"name": "sockeye salmon",
"gender": "female"
},
],
},
{
"name": "carp",
"species": [
{
"name": "grass carp",
"gender": "male"
},
{
"name": "common salmon",
"gender": "female"
},
],
},
];
const speciesCount = fish.flatMap(f => f.species).length;
console.log(speciesCount);
You could use .reduce
to accumulate the length of species
const res = fish.reduce((acc, el) => acc + el.species.length, 0)
let fish = [ { name: "salmon", species: [ { name: "atlantic salmon", gender: "male", }, { name: "sockeye salmon", gender: "female", }, ], }, { name: "carp", species: [ { name: "grass carp", gender: "male", }, { name: "common salmon", gender: "female", }, ], }, ] const res = fish.reduce((acc, el) => acc + el.species.length, 0) console.log(res)
Try this.
let count = 0;
for (let i = 0; i < fish.length; i++) {
for (let j = 0; j < fish[i][species].length; i++) {
count++;
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.