I have an array that looks like this,
[
{
"header": true
},
{
"pk": "P000",
"nest": 0
},
{
"pk": "P000-000",
"nest": 1
},
{
"pk": "P000-002",
"nest": 1
},
{
"pk": "P000-003",
"nest": 1
},
{
"pk": "P000-001",
"nest": 1
},
{
"pk": "P001",
"nest": 0
},
{
"pk": "P001-000",
"nest": 1
},
{
"pk": "P001-001",
"nest": 1
},
{
"pk": "P001-002",
"nest": 1
},
{
"pk": "P002",
"nest": 0
},
{
"pk": "P002-000",
"nest": 1
},
{
"pk": "P003",
"nest": 0
},
{
"pk": "P003-000",
"nest": 1
},
{
"pk": "P003-001",
"nest": 1
},
{
"pk": "P004",
"nest": 0
},
{
"pk": "P004-000",
"nest": 1
},
{
"pk": "P005",
"nest": 0
},
{
"pk": "P005-000",
"nest": 1
},
{
"pk": "P006-000",
"nest": 0
}
]
If a nest attribute is 0 it means it's a parent, if a nest object is 1 it's means its a child. What I am wanting to is access the above array at a certain index and count the number of nest:1
until the next nest:0
this way I can work how many children that parent has.
To count the number of occurances on nest:0
I can do thing like this,
const count = array.filter((obj) => obj.nest === 1).length;
This will give me the number child rows in the entire row, but what I just want to count the number of child rows from a certain index until next occurance of nest:0
For example how would I count the number of nest:1
from the nest:0
at index 1 until following nest:0
?
CodePudding user response:
By simply iterating over the array:
let count = 0;
for (let i = index; i < array.length && array[i].nest ! == 0; i )
count ;
CodePudding user response:
You can loop over the array starting from the provided index and keep updating the count until a 0
is encountered.
const data = [{ nest: 1 }, { nest: 1 }, { nest: 0 }, { nest: 1 }, { nest: 1 }];
const sol = (data, index) => {
let count = 0;
for (let i = index; i < data.length && data[i].nest; i ) {
count = 1;
}
return count;
};
console.log(sol(data, 0)); // 2
console.log(sol(data, 1)); // 1
console.log(sol(data, 2)); // 0
console.log(sol(data, 3)); // 2
If you have to make this query again and again for different indices then you can precompute the count at all indices beforehand, as shown below:
const data = [{ nest: 1 }, { nest: 1 }, { nest: 0 }, { nest: 1 }, { nest: 1 }];
const counts = [];
for (let i = data.length - 1; i >= 0; i--) {
if (data[i].nest) {
counts.unshift(1 (counts.length && counts[0]));
} else {
counts.unshift(0);
}
}
const queries = [0, 1, 2, 3, 4];
console.log(queries.map((index) => counts[index])); // [ 2, 1, 0, 2, 1 ]