如何在JavaScript中合并两个数组并替换前一个的值

时间:2019-07-01 01:50:22

标签: javascript jquery arrays

我有两个包含时间戳及其值的数组。

我正在使用这些数据通过HighCharts插件生成图表。

  array_1 is my default
  array_2 is my dynamic data

这是我的帮助程序方法,用于生成默认数据。

def default_chart_data
  data = []
  d = local_time_here
  for hour in 0..23 do
    data << [d.change(hour: hour, min: 0, sec: 0).to_i * 1000, rand(5..500)]
  end
  return data
end

我的目标是替换默认数组的值,并使用基于时间戳作为键的动态

,并且 ADD 默认数组array1

中不存在的其他数据

最后将其合并后对其进行排序。

  For example:

  var array1 =  [
    [1561867200000, 0],
    [1561870800000, 0], // value should change to 2
    [1561874400000, 0],
    [1561878000000, 0],
    [1561881600000, 0], // value should change to 5
  ]


  var array2 =  [
    [1561867200000, 1],
    [1561870800000, 2], // 1st matched from array1
    [1561874400000, 3],
    [1561878000000, 4],
    [1561881600000, 5], // 2nd matched from array1  
    [1561921200000, 6]
  ]



  Expected Result like, once merged:

  [
    [1561870800000, 2],
    [1561867200000, 1],
    [1561874400000, 3],
    [1561878000000, 4],
    [1561881600000, 5],
    [1561921200000, 6]
  ].sort_based_on_timestamp_here(how?)

2 个答案:

答案 0 :(得分:1)

不如@BlueWater86answer优雅(在这个问题上也有点朦胧),但是如果两个数组都已经排序,则不需要排序:

  var array1 =  [
    [1561867200000, 0],
    [1561870800000, 0], // value should change to 2
    [1561874400000, 0],
    [1561878000000, 0],
    [1561881600000, 0], // value should change to 5
  ]


  var array2 =  [
    [1561867200000, 1],
    [1561870800000, 2], // 1st matched from array1
    [1561874400000, 3],
    [1561878000000, 4],
    [1561881600000, 5], // 2nd matched from array1
    [1561921200000, 6]
  ]


var result = [];

for( var index1 = 0; index1 < array1.length; index1++ ) {
    var item1 = array1[index1];

    for( var index2 = array2.length - 1; index2 >= 0; index2-- ) {
        var item2 = array2[index2];
        if(item1[0] === item2[0]) {
            result.push(item2);
            array2.splice(index2, 1);
            break;
        }

        if(index2 != 0)
            continue;
        result.push(item2);
    }
}
for( var index2 = array2.length - 1; index2 >= 0; index2-- ) {
        result.push(array2[index2]);
}

console.log(result);

通过在添加第二个数组时反转它们,应该保持顺序正确。

答案 1 :(得分:0)

我想我了解您要做什么。

首先,我们filter array1获得不在array2中的值。

然后我们使用concat的默认值加入array2。

然后我们sort最终数组。

  var array1 =  [
    [1561867200000, 0],
    [1561870800000, 0], // value should change to 2
    [1561874400000, 0],
    [1561878000000, 0],
    [1561881600000, 0], // value should change to 5
  ]


  var array2 =  [
    [1561867200000, 1],
    [1561870800000, 2], // 1st matched from array1
    [1561874400000, 3],
    [1561878000000, 4],
    [1561881600000, 5], // 2nd matched from array1  
    [1561921200000, 6]
  ]

var defaults = array1.filter(arr1 => !array2.find(arr2 => arr2[0] === arr1[0]))
var all = defaults.concat(array2)
var sorted = all.sort((a, b) => a[0] - b[0])
console.log(sorted)