Lookup closest matching value of array and return array index number

Hi All

I have a payload 0 to 5 in non-linear fractions. i have a "look up" array[16]
How do i do the following?

  1. Find the value in the array that closest match the payload.
  2. Return the index position of this value.

Sounds like a google JavaScript problem.

Loop through your array and do some calculations and if statements

let result = array[0]   // start with first value of array
let resultIndex = 0;

array.forEach((el, index) = > {

if difference of Math.abs(el - msg.payload)  is less than the result difference  .... 
result = el
resultIndex = index
})

Math.abs() for absolute value of number

Test flow :

[{"id":"e8ed68c4.d45f68","type":"function","z":"a311c276.8fe21","name":"","func":"let array = [1,2,4,-5,6,7,8,77,-4, 45]\nlet result = array[0]   // start with first value of array\nlet resultIndex = 0;\n\n\narray.forEach((el, index) => {\n\nif (Math.abs(el - msg.payload)  < Math.abs(result -msg.payload)) {\nresult = el;\nresultIndex = index;\n}\n})\nmsg.array = array;\nmsg.result = result;\nmsg.resultIndex = resultIndex;\n\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","x":560,"y":2260,"wires":[["cd666bd5.22db58"]]},{"id":"da3c450b.a19978","type":"inject","z":"a311c276.8fe21","name":"","props":[{"p":"payload"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"-6.2","payloadType":"num","x":300,"y":2260,"wires":[["e8ed68c4.d45f68"]]},{"id":"cd666bd5.22db58","type":"debug","z":"a311c276.8fe21","name":"","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":830,"y":2260,"wires":[]}]

ps. it would be better if we had some real data to better test the results

Hi All
Thank you for your time to assist.
My function looks like this:

var myNumber = (5/15)*msg.payload
var numbers = [0, 10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120, 130, 140, 150]
var MyValue = Math.abs(numbers[0] - myNumber)
var idx = 0
for(var c = 1; c < numbers.length; c++)
{
var cMyValue = Math.abs(numbers[c] - myNumber)
if(cMyValue < MyValue)
{
idx = c
MyValue = cMyValue
}
}
msg.payload = idx
return msg

1 Like

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.