Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array of objects count and update numbering only if the boolean of top row is true

I'm struggling to get the following to work.

I have a sorted array of objects which contains No,Title, and Top (Which means the top row):

var arr = [];
arr = [
    {No: "", Title: "John", Top: true},
    {No: "", Title: "John", Top: false},
    {No: "", Title: "John", Top: false},
    {No: "", Title: "Kyle", Top: true},
    {No: "", Title: "Jonnah", Top: true},
    {No: "", Title: "Jonnah", Top: false},
    {No: "", Title: "Hyuri", Top: true},
    {No: "", Title: "Hyuri", Top: false},
    {No: "", Title: "Hyuri", Top: false},
]

I want to count and update the numbering No only if the Top is true.

So, below is the results that I expected to get:

arr = [
    {No: "1", Title: "John", Top: true},
    {No: "", Title: "John", Top: false},
    {No: "", Title: "John", Top: false},
    {No: "2", Title: "Kyle", Top: true},
    {No: "3", Title: "Jonnah", Top: true},
    {No: "", Title: "Jonnah", Top: false},
    {No: "4", Title: "Hyuri", Top: true},
    {No: "", Title: "Hyuri", Top: false},
    {No: "", Title: "Hyuri", Top: false},
]

Following is an attempt I've made:

for(var i=0;i<arr.length;i++){
    if(i!=(arr.length-1)){
        if(arr[i].Top){
            arr[i].No = i+1;
        }else{
            arr[i+1].No = arr[i].No;
        }
    }
    
}

The results that i get:

[
    {"No": 1, "Title": "John", "Top": true},
    {"No": "", "Title": "John", "Top": false},
    {"No": "", "Title": "John", "Top": false},
    {"No": 4, "Title": "Kyle", "Top": true},
    {"No": 5, "Title": "Jonnah", "Top": true},
    {"No": "", "Title": "Jonnah", "Top": false},
    {"No": 7, "Title": "Hyuri", "Top": true},
    {"No": "", "Title": "Hyuri", "Top": false},
    {"No": "", "Title": "Hyuri", "Top": false}
]

How can i get the results that i want?

like image 412
DiN CS Avatar asked Oct 20 '25 00:10

DiN CS


1 Answers

You could take a closure over count and update the object, if necessary.

const
    data = [{ No: "", Title: "John", Top: true }, { No: "", Title: "John", Top: false }, { No: "", Title: "John", Top: false }, { No: "", Title: "Kyle", Top: true }, { No: "", Title: "Jonnah", Top: true }, { No: "", Title: "Jonnah", Top: false }, { No: "", Title: "Hyuri", Top: true }, { No: "", Title: "Hyuri", Top: false }, { No: "", Title: "Hyuri", Top: false }],
    result = data.map((count => o => ({
        ...o,
        ...o.Top && { No: (++count).toString() }
    }))(0));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
like image 131
Nina Scholz Avatar answered Oct 21 '25 13:10

Nina Scholz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!