比较数组并添加?

时间:2019-02-13 18:23:09

标签: javascript jquery

我有两个数组

Data = [
"year": 2001, "count": 35,
"year": 2002, "count": 15,
"year": 2005, "count": 2
]

Years = [2000, 2001, 2002, 2003, 2004, 2005, 2006]

我想做的是:检查Years中是否存在Data,如果不存在,请在Data上加上“ count”,并加上“ count” “,为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");
    };
  })
}

5 个答案:

答案 0 :(得分:2)

如果我假设您的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);

答案 1 :(得分:1)

您可以循环使用年份:

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 < Years.length; i++) {
    if(!Data.find((e) => e.year == Years[i])) {
        Data.push({'year':  Years[i], 'count': 0})
    }
}

console.log(Data);

答案 2 :(得分:0)

使用include并在include返回false时推送它

for (var i = 0; i < Data.length; i++) {
  if(!Years.includes(Data[i].year)) years.push(Data[i].year)
}

答案 3 :(得分:0)

数据无效rn,它应该是一个对象数组:

data = [
{"year": 2001, "count": 35},
{"year": 2002, "count": 15},
{"year": 2005, "count": 2}
]

然后您可以进行比较:


for(let i = 0; i < data.length;  i++){
    if(years.includes(data[i].year){
       data[i].count++;
    }
}

PS:您的变量应采用驼峰式大小写,以避免混淆为类。

答案 4 :(得分:-1)

您可以迭代years并将缺少的年份拼接到data数组中。

var data = [{ year: 2001, count: 35 }, { year: 2002, count: 15 }, { year: 2005, count: 2 }],
    years = [2000, 2001, 2002, 2003, 2004, 2005, 2006];

years.forEach((i => year => {
    if (i >= data.length || year < data[i].year) {
        data.splice(i, 0, { year, count: 0 });
    }
    i++;
})(0));

console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }