rocketcrafter
rocketcrafter

Reputation: 57

Thymeleaf IndexOf array elemt

So, I didn't find any useful information online, so I instead ask about it. The problem is relatively simple. I want to get the index of a value in an array in Thymeleaf. I have this code:

th:attr="list=${dropdownFields != null && #arrays.contains(dropdownFields[0], y) ?
dropdownFields[1][dropdownFields[0].indexOF(y)] : null}"

It's a part of a bigger thing ofc, but I generally only want help with this. As you can see, I currently have: dropdownFields.indexOF(y) almost at the end, that's where I get confused, I want to get the same index that is found in the if statement, but now I want to use the index it was found at a different point, to get a different value. Is this somehow possible? Honestly, all that's important is the question: How do I use indexOf in Thymeleaf.

Thank you.

Upvotes: 0

Views: 623

Answers (1)

andrewJames
andrewJames

Reputation: 22012

A workaround for the lack of indexOf for your array is to convert the array to a list.

You can do this in Thymeleaf as follows:

<input th:attr="list=${dropdownFields != null && #arrays.contains(dropdownFields, y) 
    ? #lists.toList(dropdownFields).indexOf(y)
    : null}">

This assumes your Java array is an object Integer[] array not a primitive int[] array.

(You can't convert a primitive array to a list - it has to be an object array. Java does not support collections of primitives, in this way.)

So, for example, assuming the Java values as follows:

int y = 23;
Integer[] dropdownFields = new Integer[]{12, 23, 34};

Then the above Thymeleaf generates the following HTML:

<input list="1">

That 1 means the number 23 is at index 1 in the original array.

Upvotes: 2

Related Questions