在JavaScript中组合两个数组的值

时间:2016-11-04 13:32:33

标签: javascript arrays

我有一个看起来像的数组:

var data = [{"year":[1981],"weight":[3]},
            {"year":[1982],"weight":[4]},
            {"year":[1985],"weight":[7]}]

我的数据系列从1980年开始,到1986年结束。我的任务是将所有缺失的值输入到数组中;在我的情况下,最终的数组应该是:

var data = [{"year":[1980],"weight":[0]},
            {"year":[1981],"weight":[3]},
            {"year":[1982],"weight":[4]},
            {"year":[1983],"weight":[0]},
            {"year":[1984],"weight":[0]},
            {"year":[1985],"weight":[7]},
            {"year":[1986],"weight":[0]}]

我分两步完成了这项任务。首先,我创建了一个长度为7个元素的空数组(1980年 - 1986年),并使用值{"year": $CURRENT_YEAR, "weight": 0}初始化每个元素。然后我循环遍历data数组,在空数组中查找当前年份的索引,并用当前值替换yearweight字段。我的代码粘贴在下面。

我想知道代码是否可以以更优雅的方式重写。

// Create empty array
var my_array = []
var length = 7

// 1st step
year = 1980
for (var i = 0; i < length; i++) {
  my_array.push({"year": year, "weight": 0});
  year++
}

// 2nd step
for (var j = 0; j < data.length; j++) {
  curr_year = data[j]["year"][0];
  curr_weight = data[j]["weight"][0]
  var index = my_array.findIndex(function(item, i) {return item.year === curr_year})
  my_array[index] = {"year": curr_year, "weight": curr_weight}
}

4 个答案:

答案 0 :(得分:2)

最好通过.map()完成这项工作。此外,如果你有一个大的输入数组,那么首先设置一个哈希(lut)可能是明智的,例如;

var data = [{"year":[1981],"weight":[3]},
            {"year":[1982],"weight":[4]},
            {"year":[1985],"weight":[7]}],
     lut = data.reduce((p,c) => p[c.year[0]] ? p : (p[c.year[0]] = c, p), {});
   range = [1980,1986],
  result = Array(range[1]-range[0] + 1).fill()
                                       .map((_,i) => lut[i+range[0]] ? lut[i+range[0]] : {year: [i+range[0]], weight: [0]});
console.log(result);

答案 1 :(得分:1)

您可以组合2个循环并在一个循环中执行这两个步骤

// Create empty array
var my_array = []
var length = 7


year = 1980
for (var i = 0; i < length; i++) {
    // check if there is data for the year
    var index = data.findIndex(function(item, i) {return item.year === year});
    if(index > -1){ //if there is data, use it
        my_array.push({"year": data[index]["year"][0], "weight": data[index]["weight"][0]});
    }else{ //put in default data
       my_array.push({"year": year, "weight": 0});
    }
    year++;
}

答案 2 :(得分:1)

每次查找大数据中的元素索引是大数据的不良表现。我可以建议以下算法:

// Create empty object and fill it with values where keys are years
var years = {};
data.forEach(item => {
    years[item.year[0]] = item.weight[0];
});

// Result array with all years
var result = [];
var startYear = 1980;
var endYear = 1986;

// Generate our result array
for (var i = startYear; i <= endYear; i++) {

    // If property for given year (i) exists in "years" object then add it to "result" array
    // in other case add default object with weight 0
    var o = years[i] ? { year: [i], weight: [years[i]] } : { year: [i], weight: [0] };
    result.push(o);
}

答案 3 :(得分:1)

您只需find()while循环即可完成此操作。

var data = [{"year":[1981],"weight":[3]},{"year":[1982],"weight":[4]},{"year":[1985],"weight":[7]}];
                   
var i = 1980;
var result = [];

while(i <= 1986) {
  var find = data.find(e => e.year[0] == i);
  (find) ? result.push(find) : result.push({year: [i], weight: [0]});
  i++;
}

console.log(result)

您也可以先使用map()获取数组,然后使用while循环使用indexOf()

var data = [{"year":[1981],"weight":[3]},{"year":[1982],"weight":[4]},{"year":[1985],"weight":[7]}];
            
var i = 1980;
var result = [];
var years = data.map(e => e.year[0]);

while(i <= 1986) {
  var ind = years.indexOf(i);
  (ind !=  -1) ? result.push(data[ind]) : result.push({year: [i], weight: [0]});
  i++;
}

console.log(result)