# Is it possible to get the index of the array object that called a function?

**URL:** <https://discourse.processing.org/t/is-it-possible-to-get-the-index-of-the-array-object-that-called-a-function/20769>\
**Category:** Coding Questions\
**Created:** [May 12, 2020, 3:19am UTC](https://discourse.processing.org/t/is-it-possible-to-get-the-index-of-the-array-object-that-called-a-function/20769 "2020-05-12T03:19:52Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![Bassam](https://avatars.discourse-cdn.com/v4/letter/b/b38774/32.png) [@Bassam](https://discourse.processing.org/u/Bassam)\
**Post date:** [May 12, 2020, 3:19am UTC](https://discourse.processing.org/t/is-it-possible-to-get-the-index-of-the-array-object-that-called-a-function/20769/1 "2020-05-12T03:19:52Z")

</div>

So I learned some time ago on this forum that the same function can be called by a button press and it’s possible to determine which button did the pressing:

```auto
function buttonPressListener(){
    switch (this) {
        case button1:
            doTask1();
            break;
        case button2:
            doTask2();
            break;
    }
}

```

Now I want to know if it’s possible to get the array index of the button (assuming it was an array of buttons) that called the function.

```auto
button[0].mouseClicked(buttonPressListener);
button[1].mouseClicked(buttonPressListener);
function buttonPressListener(){
    //code that determines what the index 
    //of the button that called this function
}

```

---

<div class="post-metadata">

**Author:** ![GoToLoop](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/gotoloop/32/86_2.png) [@GoToLoop](https://discourse.processing.org/u/GoToLoop)\
**Post date:** [May 12, 2020, 3:50am UTC](https://discourse.processing.org/t/is-it-possible-to-get-the-index-of-the-array-object-that-called-a-function/20769/2 "2020-05-12T03:50:38Z")

</div>

> **[Array.prototype.indexOf()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf)**
>
> The indexOf() method returns the first index at which a given element can be found in the array, or -1 if it is not present.

`const idx = buttons.indexOf(this), btn = buttons[idx];`

---

<div class="post-metadata">

**Author:** ![Kevin](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/kevin/32/2297_2.png) [@Kevin](https://discourse.processing.org/u/Kevin)\
**Post date:** [May 12, 2020, 6:09am UTC](https://discourse.processing.org/t/is-it-possible-to-get-the-index-of-the-array-object-that-called-a-function/20769/3 "2020-05-12T06:09:47Z")

</div>

You could modify your `buttonPressListener` function to take a parameter, and then pass that parameter into the function using an anonymous callback function. Something like this:

```auto
button[0].mouseClicked(() => { buttonPressListener(0); });
button[1].mouseClicked(() => { buttonPressListener(1); });

```
