Find element in array

Lasse Korsgaar1
Tera Contributor

Hi,

 

I have a need in relation to arrays.

 

Ex.: I have an array that always consists of 5 elements, because I have limited my GlideRecord query to 5.

Array = [apple, lemon, orange, kiwi, banana]

I need to find the element in position 5 (banana) and store it in a variable.

 

I have found this thread, but it is the reverse activity - finding the position of the element.

Solved: How to find the position of an element in an array... - ServiceNow Community

 

Bring your magic!

Thanks.

1 ACCEPTED SOLUTION

Bert_c1
Kilo Patron
var Array = ['apple', 'lemon', 'orange', 'kiwi', 'banana'];
gs.info(Array[4]);

Results:
*** Script: banana

View solution in original post

5 REPLIES 5

Soham Saha
Tera Contributor

There are several ways to do this.

 

This way will work for any array of any length and will preserve the original array.

 

var Array = ['apple', 'lemon', 'orange', 'kiwi', 'banana'];
var fruit = (Array[Array.length-1])
gs.info(fruit)
 
Results:
***Script: banana
 
This way will give you the same result but will modify the original array. You will be removing the last element from the array and assigning that to the variable.
 
var Array = ['apple', 'lemon', 'orange', 'kiwi', 'banana'];
var fruit = (Array.pop())
gs.info(fruit)
 
Results:
***Script: banana
 
The main idea here is that you will be able to access any index in the array by just calling the array and putting the index in square brackets.
 
var Array = ['apple', 'lemon', 'orange', 'kiwi', 'banana'];
var fruit1 = (Array[4])
var fruit2 = (Array[3])
gs.info(fruit1)
gs.info(fruit2)
 
Results
***Script: banana
***Script: kiwi