我有一个2D数组,它包含这样的值:
var array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
对于每个具有相同日期值(第一个元素)的嵌套数组,我想把第二个值加起来,得到这样的值:
arrayAdd = [["10/10/2020","1400"],["O7/10/2020","200"],["03/10/2020","100"]]
我该怎么做?
var array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
function fromEntries (iterable) {
return [...iterable].reduce((obj, [key, val]) => {
obj[key] = String(obj[key] ? +obj[key] + +val : val)
return obj
}, {})
}
console.log(fromEntries(array))
逐步:
-
创建一个空对象/贴图。
-
遍历你的数组。
获取数组中每个项的第一个元素(日期),并检查该键是否已在对象中。
-
如果不是,则添加它。该值将是第二个元素(数字)。
-
如果它已经存在,则递增该值。
-
-
Object.entries
会将该对象变成一个具有所需形状的数组,如下所示:
const obj = {
"10/10/2020": "1400",
"O7/10/2020": "200",
"03/10/2020": "100",
};
console.log(Object.entries(obj));
.as-console-wrapper {
max-height: 100% !important;
}
这应该有助于你开始。
您可以执行此
const data = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
const result = Object.entries(data.reduce((res, [key, value] ) => {
return {
...res,
[key]: (res[key] || 0) + Number(value)
}
}, {}))
console.log(result)
有几种方法可以处理这个问题。
您可以比较每个日期的字符串值以查看它们是否相同,也可以将它们转换为日期对象并以这种方式进行比较。这里有一个指向MDN文档的链接,它显示了如何获得日期的基元值。
我将使用字符串值,因为在这种情况下,我将假设所有日期都以一致的格式出现。
let array = [["10/10/2020","1000"],["10/10/2020","300"],["07/10/2020","100"],["07/10/2020","100"],["03/10/2020","100"],["10/10/2020","100"]];
let arrayAdd = []
for (let valuePair of array) {
// grab just the date value
let date = valuePair[0];
// check to see if pair is in arrayAdd
let foundPair = arrayAdd.find(el => el[0] === date)
// will return undefined if nothing found
if (!foundPair) {
// if nothing found, we push the entire value and date pair
arrayAdd.push(valuePair);
} else {
// few things happening here..
// we have to convert each value to number to properly add
// once they're added, we convert that new value back into a string
// and then set the value of the found pair to that new string.
foundPair[1] = (Number(valuePair[1]) +
Number(foundPair[1])).toString();
}
}
console.log(arrayAdd);