I am incrementing the value on rank by one till the name property changes, I am using the page and rank properties to determine when that happens.
But I would also like to increment it once when the type is not equal to none and resume when it does again.
I almost have it with this, but I seem to be one step behind, as when the type returns to none still not incrementing.
const data = [
{ name: 'car', rank: 1, page: 1, type: 'another' },
{ name: 'car', rank: 2, page: 1, type: 'none' },
{ name: 'car', rank: 1, page: 2, type: 'none' },
{ name: 'car', rank: 2, page: 2, type: 'none' },
{ name: 'bike', rank: 1, page: 1, type: 'none' },
{ name: 'bike', rank: 2, page: 1, type: 'none' },
{ name: 'bike', rank: 1, page: 2, type: 'something_else' },
{ name: 'bike', rank: 2, page: 2, type: 'something_else' },
{ name: 'bike', rank: 1, page: 3, type: 'something_else' },
{ name: 'bike', rank: 2, page: 3, type: 'none' },
{ name: 'moto', rank: 1, page: 1, type: 'not_none' },
{ name: 'moto', rank: 2, page: 1, type: 'not_none' },
{ name: 'moto', rank: 1, page: 2, type: 'none' },
{ name: 'moto', rank: 2, page: 2, type: 'none' },
{ name: 'bus', rank: 1, page: 1, type: 'none' },
{ name: 'bus', rank: 2, page: 1, type: 'none' },
{ name: 'bus', rank: 1, page: 2, type: 'none' },
]
let counter = 1
const results = data.reduce((acc, obj) => {
if (obj.page === 1 && obj.rank === 1)
counter = 1
obj.rank = obj.type === 'none' ? counter++ : counter
acc.push(obj)
return acc
}, [])
console.log(results)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Desired output
[
{ name: 'car', rank: 1, page: 1, type: 'other' },
{ name: 'car', rank: 2, page: 1, type: 'none' },
{ name: 'car', rank: 3, page: 2, type: 'none' },
{ name: 'car', rank: 4, page: 2, type: 'none' },
{ name: 'bike', rank: 1, page: 1, type: 'none' },
{ name: 'bike', rank: 2, page: 1, type: 'none' },
{ name: 'bike', rank: 3, page: 2, type: 'something_else' },
{ name: 'bike', rank: 3, page: 2, type: 'something_else' },
{ name: 'bike', rank: 3, page: 3, type: 'something_else' },
{ name: 'bike', rank: 4, page: 3, type: 'none' },
{ name: 'moto', rank: 1, page: 1, type: 'not_none' },
{ name: 'moto', rank: 1, page: 1, type: 'not_none' },
{ name: 'moto', rank: 2, page: 2, type: 'none' },
{ name: 'moto', rank: 3, page: 2, type: 'none' },
{ name: 'bus', rank: 1, page: 1, type: 'none' },
{ name: 'bus', rank: 2, page: 1, type: 'none' },
{ name: 'bus', rank: 3, page: 2, type: 'none' }
]