我得到了一个由数据库填充的二维数组:
var Index = [["value1_lang1", "value1_lang2", "value1_lang3", "3,6,11,"],["value1_lang1", "value1_lang2", "value1_lang3", "37,41,97,114,"],["value2_lang1", "value2_lang2", "value2_lang3", "9,14,33,"]];
该数组将获得超过600个值。我尝试使用以下两个for循环来完成它:
for(var i = 0; i < Index.length; i++) {
for(var j = i + 1; j < Index.length; ) {
var item1 = Index[i][0]; //Only have to compare the values from lang1
var item2 = Index[j][0];
if(item1 == item2) {
var page1 = Index[i][3];
var page2 = Index[j][3];
if(page1 != page2) {
var newpages = page1 + page2;
} else {
var newpages = page1;
}
Index[i][3] = newpages;
Index.splice(j, 1);
page1 = "";
page2 = "";
newpages = "";
} else {
j++;
}
}
}
结果应如下所示:
var Index = [["value1_lang1", "value1_lang2", "value1_lang3", "3,6,11,37,41,97,114"], ["value2_lang1", "value2_lang2", "value2_lang3", "9,14,33,"]];
但实际结果如下:
var Index = [[undefined, undefined, undefined, undefined],["value1_lang1", "value1_lang2", "value1_lang3", "3,6,11,37,41,97,114,"], ["value2_lang1", "value2_lang2", "value2_lang3", "9,14,33,"]];
答案 0 :(得分:1)
根据我对要求的假设,以下应该适合你
var Index = [
["value1_lang1", "value1_lang2", "value1_lang3", "3,6,11"],
["value1_lang1", "value1_lang2", "value1_lang3", "37,41,97,114"],
["value2_lang1", "value2_lang2", "value2_lang3", "9,14,33"]
];
var map = {}; // Creating a map of unique values and value (will get updated)
for (var item of Index) {
var val = map[item[0]];
if (val) {
val[3] = val[3] + item.slice(3).join(",");
} else {
val = item;
}
map[item[0]] = val;
}
var result = []; // Will be a collection of desired values
for (var key in map) {
result.push(map[key]);
}
console.log(JSON.stringify(result));
&#13;
答案 1 :(得分:1)
您可以使用内部数组的前三个元素作为哈希表的键并推送到结果集(如果不存在)或将元素附加到索引3处。
var data = [["value1_lang1", "value1_lang2", "value1_lang3", "3,6,11,"], ["value1_lang1", "value1_lang2", "value1_lang3", "37,41,97,114,"], ["value2_lang1", "value2_lang2", "value2_lang3", "9,14,33,"]],
result = [];
data.forEach(function (a) {
var key = a.slice(0, 3).join('|');
if (!this[key]) {
this[key] = a.slice();
result.push(this[key]);
return;
}
this[key][3] += a[3];
}, Object.create(null));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }