gpt4 book ai didi

javascript - 如何根据相似度更改数组中对象的参数?

转载 作者:行者123 更新时间:2023-12-04 15:56:45 26 4
gpt4 key购买 nike

我有这个对象数组:

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 },
];

我正在尝试仅使用简单的 JavaScript 对其进行迭代以获得以下结果:

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 },
];

不幸的是,我尝试了很多不同的方法,但没有任何效果。任何提示如何实现这一目标?提前致谢。

这可能是我得到的最接近的:

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;
}
}
}

最佳答案

您可以先按score分组,然后为每个组添加位置。

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 }],
result = data
.reduce((r, o, i, a) => {
if (!i || a[i - 1].score !== o.score) r.push([]);
r[r.length - 1].push(o);
return r;
}, [])
.flatMap(a => a.map((o, i, b) => b.length === 1
? o
: { ...o, position: `${b[0].position}-${b[b.length - 1].position}` }
));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于javascript - 如何根据相似度更改数组中对象的参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68898921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com