如何将多维数组转换为此格式

时间:2017-10-04 19:20:33

标签: javascript arrays multidimensional-array

我每秒都有来自Web Socket的数据,例如



1- [["X",1],["Y",2],["Z",3]] 

2 -[["X",2],["Y",7]] 

3 -[["Y",5],["Z",1]] 

4 -[["X",7]] 
...




每次迭代的结果数组

1 - ["X",1,0],["Y",2,0],["Z",3,0]] // 0只是差异,它也可以是+或负

2 - ["X",2,1],["Y",7,5],["Z",3,0]] //第一次迭代的差异

3 - ["X",1,0],["Y",5,-2],["Z",1,-2]] //来自第二个

的差异

我迄今为止尝试过的事情

    this.socketSubscription = this.socket.messages.subscribe((message) => {
      this.prev = this.rows;

      this.rows = JSON.parse(message);
      if(this.prev){
        this.rows.forEach(element => {
          for (var index = 0; index < element.length; index++) {
            console.log(element[index]);
            let check = this.prev.find(prevElement => prevElement.find(el => el[0]));
            console.log("check"+check);
/*             if (element[0] === ())){
              console.log("here");
            } */
          }
        });
      }

1 个答案:

答案 0 :(得分:1)

您不需要for循环或嵌套find。这足够接近,应该让你走上正轨:

var results;

function process(data) {
    if (results) {
        data.forEach(element => {
            var key = element[0];
            var val = element[1];
            var index = results.findIndex(result => result[0] == key);
            var prevVal = results[index][1];
            var diff = val - prevVal;
            results[index][1] = val;
            results[index][2] = diff;
        });
    } else {
        results = data.map(element => { element[2] = 0; return element; });
    }
}

var a = [["X",1],["Y",2],["Z",3]];
var b = [["X",2],["Y",7]];
var c = [["Y",5],["Z",1]];

process(a); console.log(results); // [["X",1,0], ["Y",2, 0], ["Z",3, 0]]
process(b); console.log(results); // [["X",2,1], ["Y",7, 5], ["Z",3, 0]]
process(c); console.log(results); // [["X",2,0], ["Y",5,-2], ["Z",1,-2]]