gpt4 book ai didi

javascript - 检查动态填充的数组中的重复对象

转载 作者:行者123 更新时间:2023-11-30 11:06:28 24 4
gpt4 key购买 nike

我正在尝试构建一个数据结构,其中所有元素都将根据对象键进行分组。

一切正常,除了我无法检查新数组是否有重复的数据,因为它在 for..of 循环之外。我正在寻找一种方法来防止 pushing 另一个对象,如果新数组已经有了它的话。

当前输出(注意来自日本的字符列表出现了两次)

[
[
{ "country": "US" },
[
{ "name": "Guile", "country": "US" }
]
],
[
{ "country": "Japan" },
[
{ "name": "E. Honda", "country": "Japan" },
{ "name": "Ryu", "country": "Japan" }
]
],
[
{ "country": "Japan" },
[
{ "name": "E. Honda", "country": "Japan" },
{ "name": "Ryu", "country": "Japan" }
]
],
[
{ "country": "Thailand" },
[
{ "name": "Sagat", "country": "Thailand" }
]
]
]

预期输出

[
[
{ "country": "US" },
[
{ "name": "Guile", "country": "US" }
]
],
[
{ "country": "Japan" },
[
{ "name": "E. Honda", "country": "Japan" },
{ "name": "Ryu", "country": "Japan" }
]
],
[
{ "country": "Thailand" },
[
{ "name": "Sagat", "country": "Thailand" }
]
]
]

到目前为止我有什么

var data = [
{name: 'Guile', country: 'US'},
{name: 'E. Honda', country: 'Japan'},
{name: 'Ryu', country: 'Japan'},
{name: 'Sagat', country: 'Thailand'}
]

const getNationList = (streetFighterList) => {
let filteredList = []
for (const [index, characterData] of streetFighterList.entries()) {
// .......................................................
// looking for ways here to check if `filteredList` already
// has the data I'm trying to push. Since it's empty
// I don't know how to check its index. :(
// NOTE: indexOf() doesn't seem to work
// .......................................................
const indexOf = filteredList.indexOf(streetFighterList[index].country)
if (indexOf == -1) {
filteredList.push([
{ country: characterData.country },
streetFighterList.filter((character) => {
return character.country === characterData.country
})
])
}
}
return filteredList
}

console.log(getNationList(data))

注意:我知道鉴于 country 对象始终是唯一的,如果我改用字符串,这种数据结构会更好更容易。然而,这是一个示例数据,在现实生活中的代码中,我确实需要将它存储为一个对象。

最佳答案

我建议使用一些来验证如下

var data = [
{name: 'Guile', country: 'US'},
{name: 'E. Honda', country: 'Japan'},
{name: 'Ryu', country: 'Japan'},
{name: 'Sagat', country: 'Thailand'}
]

const getNationList = (streetFighterList) => {
let filteredList = []
for (const [index, characterData] of streetFighterList.entries()) {

const entry = filteredList.some(item => item[0].country === streetFighterList[index].country)
if (!entry) {
filteredList.push([
{ country: characterData.country },
streetFighterList.filter((character) => {
return character.country === characterData.country
})
])
}
}
return filteredList
}

console.log(getNationList(data))

关于javascript - 检查动态填充的数组中的重复对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55421969/

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