JavaScript ensure all numbers are unique and if not plus one (or more)

Viewed 302

I'm trying to place some labels on a d3 chart.

I have a DATA object with a DATA.rowOffset value for each. Basically my code calculates the DATA.rowOffset and sets it like this: d.rowOffset = Math.floor(d.total/heightSquares); but sometimes the rowOffset is the same and so the labels render on top of each other.

I need to cycle through this DATA and check for duplicates and then just +1 any duplicates.

I tried a method that looked at the previous .rowOffset and then added 1 to the current rowOffset, but that doesn't work if there are more than 2 duplicates.

I'm sure there's an easier way.... perhaps.

Edit: here's some code I tried mainly if (d.rowOffset === DATA[i-1].rowOffset) d.rowOffset++; so it checks the previous row offset. I think I need to cycle through all the data and then restart the cycle if a duplicate is found.

DATA.forEach(function(d, i) {
      d.amt = +d.amt;

      d.units = Math.floor(d.amt / squareValue);

      sumTotal = sumTotal + d.units;
      d.total = sumTotal;



      d.rowOffset = Math.floor(d.total / heightSquares);

      if (i > 0) {
        console.log(DATA[i - 1].rowOffset);
        if (d.rowOffset === DATA[i - 1].rowOffset) d.rowOffset++;
      }
1 Answers
Related