我有一个2D数组:
var arr1 = [["Egypt","Grid",50],["Egypt","Grid",10],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]]
我想检查每个数组的第一个元素,例如埃及、尼日利亚和加纳,看看它们是否重复。但我只想让它检查下一个元素而不是数组中的所有元素。如果一个或多个元素相邻重复,我希望返回一个数组,将位置2(50,10,20,60,30)的元素相加
结果应该是:
var arr2 = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60]],["Egypt","Grid",30]]
请注意,尽管有3个带有"Egypt"的数组,它只在它们相邻的地方组合。
我已经尝试了map
和for loop
,但没有任何接近工作的东西。这是我开始的内容:
arr1.map(function (unit, index, array) {
var length = array.length
if (index < length - 2) {
var next = array[index + 1][0]
if (unit[0] === next) {
}
}
})
用于检查元素是否重复。我想我接下来需要把重复到一个单独的阵列,我可以然后reduce
,但我不知道如何做到这一点。任何能给我指出正确方向的帮助都会很好。谢谢!
您可以使用一个简单的for
循环遍历除最后一个数组外的每个数组,并检查当前迭代元素的第一个元素是否与当前+1的第一个元素匹配。
如果匹配,则对每个数组的第三个元素求和并赋值给当前迭代数组,删除current+1
(此处使用splice()
)并减少i
以再次检查相同的索引。
var arr1 = [
['Egypt', 'Grid', 50],
['Egypt', 'Grid', 10],
['Nigeria', 'Grid', 20],
['Ghana', 'Grid', 60],
['Egypt', 'Grid', 30],
];
for (let i = 0; i < arr1.length - 1; i++) {
if (arr1[i][0] === arr1[i + 1][0]) {
arr1[i][2] = arr1[i][2] + arr1[i + 1][2];
arr1.splice(i + 1, 1);
i--;
}
}
console.log(arr1);
你可以创建一个grouping
数组,只有当country
和category
的最后一个元素与grouping
数组的最后一个元素不匹配或者grouping
中没有元素
可以使用for..of
loop
var arr1 = [
["Egypt", "Grid", 50],
["Egypt", "Grid", 10],
["Nigeria", "Grid", 20],
["Ghana", "Grid", 60],
["Egypt", "Grid", 30],
];
const grouping = [];
for (let [country, category, num] of arr1) {
const last = grouping[grouping.length - 1];
const [lastCountry, lastCategory, lastNum] = last ?? [];
lastCountry && lastCountry === country && lastCategory === category
? (last[2] += num)
: grouping.push([country, category, num]);
}
console.log(grouping);
/* This is not a part of answer. It is just to give the output fill height. So IGNORE IT */
.as-console-wrapper { max-height: 100% !important; top: 0; }
以下是reduce
的解决方案。为了简化解构,我选择首先将结果前置到累加器,然后最后使用reverse
:
反转该结果。
let arr = [["Egypt","Grid",60],["Nigeria","Grid",20],["Ghana","Grid",60],["Egypt","Grid",30]];
let result = arr.slice(1).reduce(([[x, y, z], ...acc], [a, b, c]) =>
a === x && b == y ? [[a, b, z + c], ...acc]
: [[a, b, c], [x, y, z], ...acc]
, [arr[0]]).reverse();
console.log(result);
var arr1 = [
["Egypt","Grid",50],
["Egypt","Grid",10],
["Egypt","Grid",10],
["Nigeria","Grid",20],
["Nigeria","Grid",20],
["Nigeria","Grid",20],
["Nigeria","Grid",20],
["Nigeria","Grid",20],
["Ghana","Grid",60],
["Egypt","Grid",30]
];
var i=0;
var j=1;
while (j<arr1.length){
if (arr1[i][0] === arr1[j][0]){
arr1[i][2] += arr1[j][2];
arr1.splice(j,1);
continue
}
i++;
j++;
}
console.log(arr1)