'Javascript replace value to increment number

i'm trying to achieve something using Javascript, my current condition is ,i have array that has same value, i need to replace the value to increment number if the value are same.

Here is my sample code

var period = ['202001', '202001', '202001', '202002', '202002', '202003', '202003', ...];

The result i'm expecting is

var period = ['0', '0', '0', '1', '1', '2', '2'];

The real case is, i want to produce a heatmap using highcharts, but i need to convert the year-month into xy coordinates.

Do you have any best suggestion about how do i solve this ?
Many Thanks...



Solution 1:[1]

Have a look below;

var period = ['202001', '202001', '202001', '202002', '202002', '202003', '202003', ];

let prevString = period[0];
let lastNumber = 0;
let reqArr = period.map(string => {
    if (string == prevString) {
        return lastNumber.toString();
    } else {
        prevString = string;
        lastNumber+=1
        return lastNumber.toString();
    }
})

console.log(reqArr);

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1