# Get the max value and compare

**URL:** <https://discourse.nodered.org/t/get-the-max-value-and-compare/68697>\
**Category:** General\
**Created:** [7 October 2022 22:42 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697 "2022-10-07T22:42:18Z")\
**Posts on this page:** 14\
**Page:** 1

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [7 October 2022 22:42 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/1 "2022-10-07T22:42:18Z")

</div>

Hi i need help, from a node i get output in json type, which has arrays(may be we can use this)  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/b/4/b4c77050a984590b3719dfb892f6194dfe175e7a.png)  
and inside each object their is a value which i need for example

```auto
->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

---

<div class="post-metadata">

**Author:** ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)\
**Post date:** [8 October 2022 00:37 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/2 "2022-10-08T00:37:13Z")

</div>

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

```auto
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;

```

```auto
[{"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":[]}]

```

---

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [8 October 2022 09:20 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/3 "2022-10-08T09:20:21Z")

</div>

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)

> [@E1cid](#):
>
> ```auto
> 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;
> 
> ```

---

<div class="post-metadata">

**Author:** ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)\
**Post date:** [8 October 2022 09:29 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/4 "2022-10-08T09:29:38Z")

</div>

```auto
//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;

```

> **[Array.prototype.reduce() - JavaScript | MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce)**
>
> The reduce() method executes a user-supplied "reducer" callback function on each element of the array, in order, passing in the return value from the calculation on the preceding element.
> The final result of running the reducer across all elements...

Which is the same as this using forEach

```auto
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;

```

---

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [8 October 2022 10:01 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/5 "2022-10-08T10:01:32Z")

</div>

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

```auto
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](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/d/6/d69480007a9dc05b74f91767d14d3b2d59cbf5c3.png)  
I have set the debug to complete msg..is it because of the payload?

---

<div class="post-metadata">

**Author:** ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)\
**Post date:** [8 October 2022 10:06 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/6 "2022-10-08T10:06:27Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [8 October 2022 10:17 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/7 "2022-10-08T10:17:24Z")

</div>

```auto
[{"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:

```auto
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

---

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [8 October 2022 10:28 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/8 "2022-10-08T10:28:12Z")

</div>

it works now...  
 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/4/c/4c97e17913329f33c2855db266101df95af3a749.png)

example code:

```auto
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;

```

---

<div class="post-metadata">

**Author:** ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)\
**Post date:** [8 October 2022 10:31 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/9 "2022-10-08T10:31:53Z")

</div>

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

```auto
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;

```

---

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [8 October 2022 10:36 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/10 "2022-10-08T10:36:33Z")

</div>

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

---

<div class="post-metadata">

**Author:** ![E1cid](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/e1cid/32/77971_2.png) [@E1cid](https://discourse.nodered.org/u/E1cid)\
**Post date:** [8 October 2022 10:40 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/11 "2022-10-08T10:40:40Z")

</div>

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

> <https://stackoverflow.com/questions/762011/what-is-the-difference-between-let-and-var>

---

<div class="post-metadata">

**Author:** ![boo](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/boo/32/67804_2.png) [@boo](https://discourse.nodered.org/u/boo)\
**Post date:** [8 October 2022 12:44 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/13 "2022-10-08T12:44:59Z")

</div>

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

 ![image](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/d/c/dc87fee72b24921cf32568b219a65c99d2195b82.png)

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 😬😬😬  
output:  
 ![NRtele](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/3X/1/6/165ecfacc55f4b951072f494c0eed1de1b7e65d8.gif)

---

<div class="post-metadata">

**Author:** ![Steve-Mcl](https://sea2.discourse-cdn.com/flex026/user_avatar/discourse.nodered.org/steve-mcl/32/4826_2.png) [@Steve-Mcl](https://discourse.nodered.org/u/Steve-Mcl)\
**Post date:** [8 October 2022 12:50 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/14 "2022-10-08T12:50:09Z")

</div>

Well done & thanks for sharing.

---

<div class="post-metadata">

**Author:** ![system](https://us1.discourse-cdn.com/flex026/uploads/nodered/original/1X/d073cd938eafa2e558d7c2cd59003b3ef4963033.png) [@system](https://discourse.nodered.org/u/system)\
**Post date:** [22 October 2022 12:50 UTC](https://discourse.nodered.org/t/get-the-max-value-and-compare/68697/15 "2022-10-22T12:50:38Z")

</div>

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