Reputation: 1585
I have data coming in every second from a Web Socket eg
1- [["X",1],["Y",2],["Z",3]]
2 -[["X",2],["Y",7]]
3 -[["Y",5],["Z",1]]
4 -[["X",7]]
...
The resultant array for each iteration
1 - ["X",1,0],["Y",2,0],["Z",3,0]]
// 0 is nothing but the difference it can also be + or minus
2 - ["X",2,1],["Y",7,5],["Z",3,0]]
// diff from first iteration
3 - ["X",1,0],["Y",5,-2],["Z",1,-2]]
// diff from second
the things i have tried till now
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");
} */
}
});
}
Upvotes: 0
Views: 62
Reputation: 43073
You don't need the for
loop or a nested find
. This is close enough and should get you on track:
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]]
Upvotes: 1