# Find the second occurrence of an object in an array

**URL:** <https://discourse.processing.org/t/find-the-second-occurrence-of-an-object-in-an-array/27309>\
**Category:** Beginners\
**Created:** [January 23, 2021, 4:46pm UTC](https://discourse.processing.org/t/find-the-second-occurrence-of-an-object-in-an-array/27309 "2021-01-23T16:46:12Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![SNICKRS](https://avatars.discourse-cdn.com/v4/letter/s/43a26b/32.png) [@SNICKRS](https://discourse.processing.org/u/SNICKRS)\
**Post date:** [January 23, 2021, 4:46pm UTC](https://discourse.processing.org/t/find-the-second-occurrence-of-an-object-in-an-array/27309/1 "2021-01-23T16:46:12Z")

</div>

Hello, I am doing a coding project but it requires me to get the second occurrence of an object in an array.

```auto
int[][] array = 
{1, 2, 3, 4},
{5, 6, 7, 8},
{1, 2, 3, 4};

```

How would you get the second occurrence of “1” in the array?

---

<div class="post-metadata">

**Author:** ![Chrisir](https://yyz2.discourse-cdn.com/flex036/user_avatar/discourse.processing.org/chrisir/32/45_2.png) [@Chrisir](https://discourse.processing.org/u/Chrisir)\
**Post date:** [January 23, 2021, 5:56pm UTC](https://discourse.processing.org/t/find-the-second-occurrence-of-an-object-in-an-array/27309/2 "2021-01-23T17:56:37Z")

</div>

Your array is not valid.

**1D array**

When you mean a 1D array:

```auto

int[] arrayMy = 
  {
  1, 2, 3, 4, 
  5, 6, 7, 8, 
  1, 2, 3, 4
};

int count=0;
int result = -1; 

for (int i = 0; i<arrayMy.length; i++) {
  if (arrayMy[i] == 1) 
    count++;
  if (count==2) {
    println(i);
    result = i; 
    break;
  }
}//for 

println(result);

```

* * *

**OR when you mean a 2D array**

```auto
// 2D array / grid
int[][] arrayMy = 
  { 
  {1, 2, 3, 4}, 
  {5, 6, 7, 8}, 
  {1, 2, 3, 4}
};

int count=0;
int result = -1;
int result2 = -1; 

// nested for-loop 
for (int i = 0; i<arrayMy.length; i++) {
  for (int i2 = 0; i2<arrayMy[i].length; i2++) {
    if (arrayMy[i][i2] == 1) 
      count++;
    if (count==2) {
      result = i;
      result2 = i2;
      break;
    }
  }//for
}//for

println(result, result2);

```

---

<div class="post-metadata">

**Author:** ![SNICKRS](https://avatars.discourse-cdn.com/v4/letter/s/43a26b/32.png) [@SNICKRS](https://discourse.processing.org/u/SNICKRS)\
**Post date:** [January 23, 2021, 8:05pm UTC](https://discourse.processing.org/t/find-the-second-occurrence-of-an-object-in-an-array/27309/3 "2021-01-23T20:05:43Z")

</div>

Thank you, but the first time I tried implementing this it didn’t work. However, then I saw that I kept redefining the count variable in the for loop. After I changed where the declaration was, it worked! Thank you!
