Andrej Andrej - 3 months ago 19
Javascript Question

Combine values from two arrays in JavaScript

I have an array which looks like:

var data = [{"year":[1981],"weight":[3]},

My data series starts with year 1980 and ends with year 1986. My task is to input all missing values into the array; in my case the final array should be:

var data = [{"year":[1980],"weight":[0]},

I implemented this task in two steps. First I created an empty array with length of seven elements (for years 1980 - 1986) and initialize each element with value
{"year": $CURRENT_YEAR, "weight": 0}
. Then I loop through
array, find index of current year in the empty array and replace
fields with current values. My code is pasted below.

I wonder if the code could be rewritten in a more elegant way.

// 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});

// 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}


It's best to do this job by .map() Besides if you have a large input array it might be wise to set up a hash (lut) in the first place such as;

var data = [{"year":[1981],"weight":[3]},
     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]});