Get the max value and compare

Hi i need help, from a node i get output in json type, which has arrays(may be we can use this)
image
and inside each object their is a value which i need for example

->array[2]
->0: object
  ->x = 1
->1: object
  ->x= 2

I want to collect all the value of x from each object ( array can increase , wont be just 2 as in example, as when more data's are collected) .
Next find the max value of x and compare to which object it actually belongs. giving the object number as output . soo from their i can use object number to find other values of under the object
this is to find the last value changes . because the ouput i get does not send form low to high or high to low just send randomly , thats why i want to find the latest object soo i can get the values from that object.
Goal ===> is to find the object number based on highest value of x
if im not clear please reply i can try again.
hoping for reply

This should return a payload object containing max and index. It returns the index of the first max starting from index 0.

let start = msg.payload[0].x;
msg.payload = msg.payload.reduce((acc,obj,index) =>{
    if(obj.x > acc.max){ // >= to find last max
        acc = {
            max : obj.x,
            index: index
            };
    }
    return acc;
},{index: 0,max: start});
return msg;
[{"id":"c190d7cc692f8710","type":"inject","z":"452103ea51141731","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"x\":1},{\"x\":3},{\"x\":3},{\"x\":2}]","payloadType":"json","x":270,"y":660,"wires":[["948f7e8e561111de"]]},{"id":"948f7e8e561111de","type":"function","z":"452103ea51141731","name":"function 10","func":"let start = msg.payload[0].x;\nmsg.payload = msg.payload.reduce((acc,obj,index) =>{\n    if(obj.x > acc.max){\n        acc = {\n            max : obj.x,\n            index: index\n            };\n    }\n    return acc;\n},{index: 0,max: start});\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":470,"y":660,"wires":[["3822869f1f68b65d"]]},{"id":"3822869f1f68b65d","type":"debug","z":"452103ea51141731","name":"debug 18","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"false","statusVal":"","statusType":"auto","x":500,"y":700,"wires":[]}]
1 Like

thanks man it works crazy ....if you dont mind i want to know how this works? Im trying to learn as i do(kind of 40% understood but this is kind of pro level code for me to understand)

//sets start value used later in the initial value of aac.max
let start = msg.payload[0].x; 
//start looping through the array using reduce()
// acc is the output , obj is each object in the array in turn, index is the current index in loop
msg.payload = msg.payload.reduce((acc,obj,index) =>{
   // if new obj is greater set up new values to acc
    if(obj.x > acc.max){ // >= to find last max
        acc = {
            max : obj.x,
            index: index
            };
    }
   // return the current acc back to reduce loop ready fo next object
    return acc;
},
// set up initial start values of acc
{index: 0,max: start});
return msg;

Which is the same as this using forEach

let output = {index: 0,max: msg.payload[0].x};
msg.payload.forEach((obj,index) =>{
    if(obj.x > output.max){
        output = {
            max : obj.x,
            index: index
            };
    }
});
msg.payload = output;
return msg;
1 Like

hi im trying to merge al stuffs but i cant get the output in debug

let start = msg.payload[0].added_on;
msg.payload = msg.payload.reduce((acc,obj,index) =>{
    if (obj.added_on > acc.max){
        acc = {
            max: obj.added_on,
            index: index
            };
    }
    return acc;
},{index: 0,max: start});


var x = msg.payload.index
var name = msg.payload[x].name
var hash = msg.payload[x].hash
var timeadded = msg.payload.max
var sensor = Number(timeadded) * 1000;	  // to milliseconds
var dif = Date.now() - sensor;	  // Date.now() returns the number of ms, not a date object
var z = {};
if (dif <= 5 * 60 * 1000) {   // if less than 5min
    //var addtwo = new Date(sensor + 2 * 60 * 60 * 1000);   // sensor time +2h like in the previous example
    var time1 = (new Date(sensor)).toLocaleString("IST", {
        weekday: 'short',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        hourCycle: 'h12',
        minute: '2-digit',
        timeZone: "Asia/Kolkata"
    });
    var time2 = time1.replace(/,/g, '');
    z = time2   // to string, assuming you're in india or similar

} else {
    z = "false";
}
msg.start = start;
msg.max = msg.payload.max;
msg.z = z;
msg.name = name;
msg.hash = hash;
msg.timeadded = timeadded;
//msg.array = array;
return msg;

only shows the
image
I have set the debug to complete msg..is it because of the payload?

Please supply a example flow, containing an inject node with the test input data. Also show us an example of the expected output.

[{"id":"e960bce4c7bccaa7","type":"inject","z":"3d8a22efe6ba1aba","name":"","props":[{"p":"payload"},{"p":"topic","vt":"str"}],"repeat":"","crontab":"","once":false,"onceDelay":0.1,"topic":"","payload":"[{\"added_on\":1,\"name\":\"a\",\"hash\":12345},{\"added_on\":7,\"name\":\"b\",\"hash\":54321},{\"added_on\":120,\"name\":\"c\",\"hash\":7777},{\"added_on\":120,\"name\":\"d\",\"hash\":11111}]","payloadType":"json","x":3025.60009765625,"y":2558.800048828125,"wires":[["6fa48b3d59fba989","053ffca12d0307e9"]]},{"id":"6fa48b3d59fba989","type":"function","z":"3d8a22efe6ba1aba","name":"function 28","func":"let start = msg.payload[0].added_on;\nmsg.payload = msg.payload.reduce((acc,obj,index) =>{\n    if(obj.added_on > acc.max){\n        acc = {\n            max : obj.added_on,\n            index: index\n            };\n    }\n    return acc;\n},{index: 0,max: start});\nmsg.start = start;\nvar x = msg.payload.index\nvar name = msg.payload[x].name\nvar hash = msg.payload[x].hash\nvar timeadded = msg.payload.max\nvar sensor = Number(timeadded) * 1000;\t  // to milliseconds\nvar dif = Date.now() - sensor;\t  // Date.now() returns the number of ms, not a date object\nvar z = {};\nif (dif <= 5 * 60 * 1000) {   // if less than 5min\n    //var addtwo = new Date(sensor + 2 * 60 * 60 * 1000);   // sensor time +2h like in the previous example\n    var time1 = (new Date(sensor)).toLocaleString(\"IST\", {\n        weekday: 'short',\n        month: 'short',\n        day: 'numeric',\n        hour: '2-digit',\n        hourCycle: 'h12',\n        minute: '2-digit',\n        timeZone: \"Asia/Kolkata\"\n    });\n    var time2 = time1.replace(/,/g, '');\n    z = time2   // to string, assuming you're in india or similar\n\n} else {\n    z = \"false\";\n}\nmsg.start = start;\nmsg.max = msg.payload.max;\nmsg.z = z;\nmsg.name = name;\nmsg.hash = hash;\nmsg.timeadded = timeadded;\n//msg.array = array;\nreturn msg;\nreturn msg;","outputs":1,"noerr":0,"initialize":"","finalize":"","libs":[],"x":3245.60009765625,"y":2558.800048828125,"wires":[["755d46562a25e0a1"]]},{"id":"755d46562a25e0a1","type":"debug","z":"3d8a22efe6ba1aba","name":"debug 90","active":true,"tosidebar":true,"console":false,"tostatus":false,"complete":"true","targetType":"full","statusVal":"","statusType":"auto","x":3485.60009765625,"y":2538.800048828125,"wires":[]}]

what i want the result to be:

max: 
name: 
hash: 
index:

use case is to get the name , hash and max from the index we found and you that to find the values inside of that object

it works now...
image

example code:

let start = msg.payload[0].added_on;
msg.abc = msg.payload.reduce((acc,obj,index) =>{
    if(obj.added_on > acc.max){
        acc = {
            max : obj.added_on,
            index: index
            };
    }
    return acc;
},{index: 0,max: start});

msg.start = start;
var x = msg.abc.index
var name = msg.payload[x].name
var hash = msg.payload[x].hash
var timeadded = msg.abc.max
var sensor = Number(timeadded) * 1000;	  // to milliseconds
var time1 = (new Date(sensor)).toLocaleString("IST", {
    weekday: 'short',
    month: 'short',
    day: 'numeric',
    hour: '2-digit',
    hourCycle: 'h12',
    minute: '2-digit',
    timeZone: "Asia/Kolkata"
});
var time2 = time1.replace(/,/g, '');
var z = time2   // to string, assuming you're in india or similar
msg.index = x;
msg.start = start;
msg.z = z;
msg.name = name;
msg.hash = hash;
msg.timeadded = timeadded;
//msg.array = array;
return msg;
return msg;

Your added_ons are not unix timestamps that are within 5mins so unable to test this, other than that this should work. uable to test fully

let output = {index: 0,max: msg.payload[0].added_on};
msg.payload.forEach((obj,index) =>{
    if(obj.added_on > output.max){
        output = {
            max : obj.added_on,
            index: index
            };
    }
});

let x = output.index
let name = msg.payload[x].name
let hash = msg.payload[x].hash
let timeadded = output.max
let sensor = Number(timeadded) * 1000;	  // to milliseconds
let dif = Date.now() - sensor;	  // Date.now() returns the number of ms, not a date object
let z = {};
if (dif <= 5 * 60 * 1000) {   // if less than 5min
    //var addtwo = new Date(sensor + 2 * 60 * 60 * 1000);   // sensor time +2h like in the previous example
    let time1 = (new Date(sensor)).toLocaleString("IST", {
        weekday: 'short',
        month: 'short',
        day: 'numeric',
        hour: '2-digit',
        hourCycle: 'h12',
        minute: '2-digit',
        timeZone: "Asia/Kolkata"
    });
    let time2 = time1.replace(/,/g, '');
    z = time2   // to string, assuming you're in india or similar

} else {
    z = "false";
}
msg.payload = {original:msg.payload}
msg.payload.max = output.max;
msg.payload.z = z;
msg.payload.name = name;
msg.payload.hash = hash;
msg.payload.timeadded = timeadded;
msg.payload.index = output.index;
return msg;
1 Like

this works perfect but why use let ?
whats the difference between let and var?

let is preferred to var as var set up a global variable, let is scoped to { } blocks

2 Likes

thanks @E1cid @Steve-Mcl @C.Sa for helping. I have finally made what i need
my flow

Created this...soo i can send any torent link in telergam and it will automatically download and save to radarr or sonarr depending on the type selected and sonarr /radar will process and send to jellyfin :grimacing::grimacing::grimacing:
output:
NRtele

1 Like

Well done & thanks for sharing.

1 Like

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