在请求一些用户图片之后,我最终得到了这样一个数组:
[
{ label: "portrait", owner: "Jon" },
{ label: "house", owner: "Jim" },
{ label: "portrait", owner: "Jim" },
{ label: "portrait", owner: "Jane" },
{ label: "cat", owner: "Jane" }
]
我需要突出显示label
在数组中多次出现的项目(此处为“portrait”)。
理想情况下,数组中label
再次出现以后的项目会有一个标记(A),最后一次出现另一个标记(B)(即两个Jon的而Jim的肖像被标记为A,而Jane则被标记为B)。
非常感谢任何帮助!
答案 0 :(得分:1)
我不确定你要做什么,但也许你只需要汇总数据?
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"]}
] */
因为发布随机代码很有趣而且你知道它!
答案 1 :(得分:1)
我建议循环遍历图片数组并为每个对象添加一个标记成员,具体取决于它是否重复。请参阅下面的示例。它将指定带有'A'的副本和带有'B'的最后副本的任何内容。任何不重复的内容都不会被标记。
var picture_array = [
{label: 'portrait', owner: "Jon"},
{label: 'house', owner: "Jim"},
{label: 'portrait', owner: "Jim"},
{label: 'portrait', owner: "Jane"},
{label: 'cat', owner: "Jane"}
],
length = picture_array.length;
//Loop through picture_array
for(var i = 0; i < length; i++) {
var picture = picture_array[i],
label = picture.label;
//If picture has already been flagged, go the the next picture
if (picture.flagged) {
continue;
}
//Loop through rest of the array to compare duplicate labels
var picture_a = picture;
for(var j = i + 1; j < length; j++) {
var picture_b = picture_array[j];
//If picture_a matches picture_b then flag both of them appropriately
if (picture_a.label == picture_b.label) {
picture_a.flagged = 'A';
picture_b.flagged = 'B';
picture_a = picture_b;
}
}
}