0

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");
            } */
          }
        });
      }
2
  • Do you have to compare values on index or on keys? You are getting different keys each time as I can see Commented Oct 4, 2017 at 19:30
  • i need to compare the incoming values with the prev and if there is a cahnage jsut list that and keep on doing it Commented Oct 4, 2017 at 19:34

1 Answer 1

1

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]]
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.