gpt4 book ai didi

javascript - 标记数组中的重复项

转载 作者:塔克拉玛干 更新时间:2023-11-03 06:05:10 25 4
gpt4 key购买 nike

在请求了一些用户图片后,我得到了一个这样的数组:

[
{ label: "portrait", owner: "Jon" },
{ label: "house", owner: "Jim" },
{ label: "portrait", owner: "Jim" },
{ label: "portrait", owner: "Jane" },
{ label: "cat", owner: "Jane" }
]

我需要突出显示其 label 在数组中出现多次的项目(此处:“portrait”)。

理想情况下,label 在数组中 later 再次出现的项目会有一个标志 (A),最后一次出现 (即 Jon 和 Jim 的肖像都标记为 A,而 Jane 的肖像标记为 B)。

如有任何帮助,我们将不胜感激!

最佳答案

我不确定您要做什么,但也许您只需要聚合数据?

var data = [
{ name: "portrait", owner: "Jon" },
{ name: "house", owner: "Jim" },
{ name: "portrait", owner: "Jim" },
{ name: "portrait", owner: "Jane" },
{ name: "cat", owner: "Jane" }
];

var byName = {};

for (var i = 0, l = data.length; i < l; ++i) {
if (!byName[data[i].name]){
byName[data[i].name] = [];
}
byName[data[i].name].push(data[i].owner);
}

// byName == {portrait: ["Jon", "Jim", "Jane"], house: ["Jim"], cat: ["Jane"]}

var byOwner = {};

for (var i = 0, l = data.length; i < l; ++i) {
if (!byOwner[data[i].owner]) {
byOwner[data[i].owner] = [];
}
byOwner[data[i].owner].push(data[i].name);
}

或者你可能更喜欢这个:

var data = [
{ name: "portrait", owner: "Jon" },
{ name: "house", owner: "Jim" },
{ name: "portrait", owner: "Jim" },
{ name: "portrait", owner: "Jane" },
{ name: "cat", owner: "Jane" }
];

var byName = [];

for (var i = 0, l = data.length; i < l; ++i) {
var done = false;
for (var j = 0, k = data.length; j < k; ++j) {
if (byName[j] && byName[j].name == data[i].name) {
byName[j].data.push(data[i].owner);
done = true;
}
}
if (!done) {
byName.push({name: data[i].name, data: [data[i].owner]});
}
}

/*
byName == [
{name: "portrait", data: ["Jon", "Jim", "Jane"]},
{name: "house", data: ["Jim"]},
{name: "cat", data: ["Jane"]}
] */

因为发布随机代码很有趣而且你知道这一点!

关于javascript - 标记数组中的重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1832261/

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