我有两个数组
Data = [
"year": 2001, "count": 35,
"year": 2002, "count": 15,
"year": 2005, "count": 2
]
Years = [2000, 2001, 2002, 2003, 2004, 2005, 2006]
我想要做的是:检查Data
中是否存在Years
,如果不存在,则将“year”添加到Data中
,“计数”为 0。
到目前为止我所能做的就是检查它们是否在那里。
Data = [
"year": 2001, "count": 35,
"year": 2002, "count": 15,
"year": 2005, "count": 2
]
Years = [2000, 2001, 2002, 2003, 2004, 2005, 2006]
for (var i = 0; i < Data.length; i++) {
$(Years).each(function(value) {
if (Data.indexOf(Years[value]) != -1) {
console.log("missing one");
};
})
}
最佳答案
如果我假设您的Data
是一个对象数组,那么您可以像这样继续:
const Data = [
{"year": 2001, "count": 35},
{"year": 2002, "count": 15},
{"year": 2005, "count": 2}
];
const Years = [2000, 2001, 2002, 2003, 2004, 2005, 2006];
Years.forEach(x =>
{
if (!Data.some(({year}) => year === x))
Data.push({year: x, count: 0});
})
console.log(Data);
// If you need to sort by year, then you could do this:
Data.sort((a,b) => a.year - b.year);
console.log(Data);
如果你追求性能,那么你可以先创建一个Set()已经存在的年份,以便以后改进推送算法。
const Data = [
{"year": 2001, "count": 35},
{"year": 2002, "count": 15},
{"year": 2005, "count": 2}
];
const Years = [2000, 2001, 2002, 2003, 2004, 2005, 2006];
const dataYears = new Set(Data.map(({year}) => year));
Years.forEach(x =>
{
if (!dataYears.has(x))
Data.push({year: x, count: 0});
})
console.log(Data);
关于javascript - 比较数组并相加?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54676986/