Getting An Item's Index Position

I have an array like:

[
    {
        "id": "1",
        "value": "abc"
    },
    {
        "id": "2",
        "value": "def"
    },
    {
        "id": "3",
        "value": "hij"
    }
]

and I need to check the position of the item with id = 2 so that I can fetch the related item from another array like:

[
    "123",
    "456",
    "789"
]

based on its position. Obviously with JavaScript I could do something like:

const array = ['apple', 'banana', 'cherry'];

const bananaIndex = array.findIndex(element => element === 'banana');

is there an equivalent function that I can use with Make? I’d prefer not to loop through the entire array with an iterator - if possible - to avoid wasting operations.

If the id is always 1-indexed, you can use the built-in function map & first, followed by a parseNumber

Screenshot_2023-12-08_231211
{{ parseNumber(first(map( array1; "id"; "value"; "def" ))) }}

to get 2

Screenshot_2023-12-08_231253

Then you can use the built-in function get on the second array to get the indexed value

Screenshot_2023-12-09_001223
{{ get( array2; index ) }}

Output

Screenshot_2023-12-09_001235

Once you set this up, you can easily see that you can combine the steps into a single module/field:


{{ get(array2; parseNumber(first(map(array1; "id"; "value"; "def")))) }}


If you want to learn more about Make, you can read up in the Help Center. I also recommend doing the tutorials in the Make Academy, and learn advanced skills like how to make custom apps to any API in the Make Partner Training Portal - both have certificates for successful completion.

1 Like

Thanks for this! I haven’t had a chance to try it yet but it looks like exactly what I need.

I’m not 100% sure what you mean here though, would you mind explaining when the id might not be 1-indexed?

2 Likes

I’ve just tried this and unfortunately it’s not working for me. There’s a couple of issues -

  1. I need to search the array based on the id
  2. If I use {{parseNumber(first(map(1.items; "value"; "id"; 2)))}} then I get an error:

The operation failed with an error. Failed to map ‘0.value’: Function ‘parseNumber’ finished with error! ‘e’ is not a valid number or using unsuitable separator.

I’ve tweaked my JSON slightly to produce an array -

{
    "items": [
        {
            "id": "1",
            "value": "abc"
        },
        {
            "id": "2",
            "value": "def"
        },
        {
            "id": "3",
            "value": "hij"
        }
    ]
}

Edit

I’ve just realised that you might have thought that the id would match the item’s position in the array, it’s not, the id could be a, b, c instead :sweat_smile: