Could someone suggest how to approach this please? I need to display a position in a JavaScript loop using "i" but would like to keep the same position if number of points are the same. Please see the simplified screenshot.
I tried different types of loops but couldn't achieve the desired effect.
CodePudding user response:
You've pretty much answered your question already. Just don't count up i
when the points are the same, while looping through your points.
Without any code example I just assumed your points were stored in an array.
const points = [6, 4, 2, 2, 2, 1];
let i = 0;
points.forEach((point, index) => {
if (point !== points[index - 1]) {
i ;
}
console.log(i); // 1, 2, 3, 3, 3, 4
});
This should be your expected result.
Note that his isn't the only solution to the problem, just one of many on how to loop though and count something up. You can use a regular for loop, forEach like I did, while, or whatever you want.
Here's another solution that might be fun, using Array.reduce to create a new Array of Positions
const points = [6, 4, 2, 2, 2, 1];
const positions = points.reduce((acc, point, index) => {
if (point !== points[index - 1]) {
acc.push(acc[index - 1] 1 || 1);
} else {
acc.push(acc[index - 1]);
}
return acc;
}, []);
console.log(positions); // [1, 2, 3, 3, 3, 4]