Sunday, 4 June 2017

Incrementing & sorting name-value pairs in JS/Node-Red

I am receiving JSON formatted messages via MQTT in node-red and would like to create a running list that keeps count of the value of a certain name and increments the value pair as a qty.

An example would be like this:

// Create the object
var array = {}

// First MQTT JSON message comes in 
msg.payload = 'banana'
array = {'banana':1}

// Second MQTT JSON message comes in
msg.payload = 'banana'
array = {'banana':2}

// Third MQTT JSON message comes in
msg.payload = 'orange'
array = {'banana':2,'orange':1}

I then want to sort the array by the values and pick out the top 5 name-value pairs and report their name and value out to separate msg objects.

My questions are as follows:

  • How can I increment the values inside the array once I read them into the code?
  • How can I sort the array by name value pair values?
  • How can I determine if a name already exists in the array?
  • If the name does not exist in the array, how can I add it in?


via Bryan Licata

No comments:

Post a Comment