如何编写以下数组格式代码的清洁版本?

时间:2018-01-22 07:20:04

标签: javascript arrays ecmascript-6 functional-programming

我有两个数组:

var test = [
  ["20180115", "0"],
  ["20180116", "0"],
  ["20180117", "0"],
  ["20180118", "0"],
  ["20180119", "0"],
  ["20180120", "0"],
  ["20180121", "0"]]

var test2 = [
  ["obj1", "20180115", "2"],
  ["obj2", "20180117", "8"], 
  ["obj3", "20180115", "1"],
  ["obj4", "20180118", "1"],
  ["obj5", "20180117", "3"]]

我想将test2数组格式化为:

// sum the same day(or same string is ok) value and others add zero
var result = [
  ["20180115", "3"],   // 2+1
  ["20180116", "0"], 
  ["20180117", "11"],  // 8+3
  ["20180118", "1"],   // 1
  ["20180119", "0"],
  ["20180120", "0"],
  ["20180121", "0"]]

这是我目前的解决方案:

// sum the same day's data

let sumData = []
test.map(row => {
    const foundData = sumData.find(data => data[0] === row[1])
    let currentData = []
    if (foundData) {
        foundData[1] += row[2]
    } else {
        currentData = [row[1], parseInt(row[2], 10)]
        sumData.push(currentData)
    }
})

// use test2's date to formate new data

test = test2.map(row => {
    const foundData = sumData.find(data => data[0] === row[0])
    if (foundData) {
        row[1] = parseInt(row[1], 10) + parseInt(foundData[1], 10)
    }
    return row
})       

代码有效,但我认为这不是一个非常干净的解决方案。是否有更好或更清洁的方法来实现这一目标?

1 个答案:

答案 0 :(得分:0)

您可以使用Map以更快的速度访问具有相同日期的数组



var test = [["20180115", "0"], ["20180116", "0"], ["20180117", "0"], ["20180118", "0"], ["20180119", "0"], ["20180120", "0"], ["20180121", "0"]],
    test2 = [["obj1", "20180115", "2"], ["obj2", "20180117", "8"], ["obj3", "20180115", "1"], ["obj4", "20180118", "1"], ["obj5", "20180117", "3"]],
    map = new Map();
    result = test.map(([d, v]) => map.set(d, [d, v]).get(d));

test2.forEach(([, d, v]) => map.get(d)[1] = (+map.get(d)[1] + +v).toString());

console.log(result);

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