I've encountered an array of objects like this:
const data = [
{ position: 1, name: "a", score: 9000 },
{ position: 2, name: "b", score: 8000 },
{ position: 3, name: "c", score: 6000 },
{ position: 3, name: "c", score: 6000 },
{ position: 4, name: "d", score: 6000 },
{ position: 5, name: "e", score: 6000 },
{ position: 6, name: "f", score: 6000 },
{ position: 7, name: "g", score: 4000 },
{ position: 8, name: "h", score: 3000 },
{ position: 9, name: "i", score: 2500 },
{ position: 10, name: "j", score: 2500 },
{ position: 11, name: "k", score: 1000 },
{ position: 12, name: "l", score: 1000 },
];
My goal is to loop through it using basic JavaScript to achieve this desired outcome:
const data = [
{ position: "1", name: "a", score: 9000 },
{ position: "2", name: "b", score: 8000 },
{ position: "3-6", name: "c", score: 6000 },
{ position: "3-6", name: "c", score: 6000 },
{ position: "3-6", name: "d", score: 6000 },
{ position: "3-6", name: "e", score: 6000 },
{ position: "3-6", name: "f", score: 6000 },
{ position: "7", name: "g", score: 4000 },
{ position: "8", name: "h", score: 3000 },
{ position: "9-10", name: "i", score: 2500 },
{ position: "9-10", name: "j", score: 2500 },
{ position: "11-12", name: "k", score: 1000 },
{ position: "11-12", name: "l", score: 1000 },
];
I've experimented with several methods, but none have yielded the desired result. Any suggestions on how to accomplish this? Thank you in advance.
This function is the closest I've come so far:
function placement() {
let repeat=0;
for (let i = 0; i < data.length; i++) {
let counter = 0;
for (let j = 0; j < data.length; j++) {
if (data[i].score == data[j].score) {
if(data[i].position==data[j].position){
repeat++;
}
counter++;
}
}
if (counter > 1) {
let k;
let start=data[i].position;
for (k = i; k < i + counter-1; k++) {
data[k].position =
start + "-" + data[i + counter-1].position;
}
i=k;
}
}
}