Search for same value in two arrays

Hello all.
I have two arrays that contain a dynamic number of objects (per input).
Screenshot_9

I am trying to do the following:
For each object in the first array, check if a certain value exists in any of the objects in the second array, and if so extract another value from that object.

I've tried doing so with the following function:

var array1 = msg.payload[0];
var array2 = msg.payload[1];
for(let i = 0; i < array2.length; i++){
    if (array2[i]["order_number"] === array1[i]["order_number"]){
        array2.push({"city" : array1[i]["city"]})
    }
}
msg.payload = array2;
return msg;

This works fine only if one of the arrays contain a single object. Any more than that and I receive an "order_number" undefined.

I've tried looping through the entire second array within the first loop with the following:

var array2 = msg.payload[0];
var array1 = msg.payload[1];
for(let i = 0; i < array1.length; i++){
    for(let i = 0; i < array2.length; i++){
    if (array1[i]["order_number"] === array2[i]["order_number"]){
        array1.push({"city" : array2[i]["city"]})
    }
}}
msg.payload = array1;
return msg;


This however causes my node-red to crash each time I inject a payload.
What am I doing wrong?

Thanks for any help.

In the last example you added, you are using the same index for both arrays, and that will never work for what you're trying to do, because you're just comparing the objects with the same index in both arrays multiple times.

Try changing the index names:

var array2 = msg.payload[0];
var array1 = msg.payload[1];
for(let i = 0; i < array1.length; i++){
    for(let j = 0; j < array2.length; j++){
    if (array1[i]["order_number"] === array2[j]["order_number"]){
        array1.push({"city" : array2[j]["city"]})
    }
}}
msg.payload = array1;
return msg;

Thanks, I’ll check it out and post an update

As expected, your advice solved my issue. Much thanks.

1 Like

You're welcome.

You should be extra careful with the index names in nested loops, and never repeat their names.

I usually go with i/j/k or x/y/z for different levels of nesting to avoid precisely this problem, but you can name them whatever you want as long as each identifier is unique (unless you work with diagonals in bidimensional arrays, but then you only need one level and one index to loop through).

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