在JavaScript数组中插入缺少的值

时间:2016-10-31 15:34:34

标签: javascript sql arrays

我有以下JavaScript代码,它使用sql.js库与远程SQL数据库进行通信。

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://dl.dropboxusercontent.com/u/540963/test.sqlite', true);
xhr.responseType = 'arraybuffer';
var output = [];

xhr.onload = function(e) {
  var uInt8Array = new Uint8Array(this.response);
  var db = new SQL.Database(uInt8Array);
  var data = db.exec("SELECT year, weight FROM freq_data WHERE doi = 'D007266'");

  $.each(data[0].values, function(key, value) {
    output.push({'year': value[0], 'weight': value[1]});
  });
};
xhr.send();

输出存储在output数组中。例如,对于给定的数组,数据如下:

{ year=1996,  weight=3}
{ year=1999,  weight=2}
{ year=2004,  weight=5}
{ year=2005,  weight=3}
{ year=2006,  weight=2}

数据存在一些差距;例如,1997年,1998年,2000年至2003年没有入境。我想知道如何用0值来填补缺失年份的数据,最终得到:

{ year=1996,  weight=3}
{ year=1997,  weight=0}
{ year=1998,  weight=0}
{ year=1999,  weight=2}
...
{ year=2006,  weight=2}

最合适的方法是什么?

1 个答案:

答案 0 :(得分:1)

假设数据按年份排序,您可以使用.reduce(),如下所示:

var data = [ { year: 1996,  weight: 3},
    { year: 1999,  weight: 2},
    { year: 2004,  weight: 5},
    { year: 2005,  weight: 3},
    { year: 2006,  weight: 2} ];
    
var final = data.reduce(function(prev, curr, index, arr) {
  prev.push(curr);
  if (index < arr.length - 1) {
    var nextYearInData = arr[index + 1].year;
    var yearToAdd = curr.year + 1;
    while (yearToAdd < nextYearInData) {
      prev.push({year: yearToAdd, weight: 0});
      yearToAdd++;
    }
  }
  return prev;
}, []);

console.log(final)