Lena
Lena

Reputation: 39

filter objects but return index and not object itself

I'd like to filter objects with a specific class assigned. I need the index position of them. here's my js code:

arr = $('table td').filter('.class', function() {
    return $(this).index()
});
console.log(arr);

this returns all tds with the class .class assigned. but I'd like to have their index position. how can I achieve that? I've also tried to figure it out using grep. same problem there.

Upvotes: 0

Views: 100

Answers (2)

charlietfl
charlietfl

Reputation: 171690

Use map() to return a new array based on values derived from the matching elements

const arr = $('table td.class').map((i, el) => $(el).index()).get()

console.log(arr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <td class="class"></td>
    <td></td>
    <td></td>
    <td class="class"></td>
    <td></td>
  </tr>

</table>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 371049

I think the way to approach this would be to use a generic iteration method and push the index to an array when such an element is found:

const arr = [];
$('table td').each(function(i) {
  if (this.matches('.class')) {
    arr.push(i);
  }
});

No need for a big library like jQuery for something this trivial, though:

const arr = [];
const tds = document.querySelectorAll('table td');
for (let i = 0; i < tds.length; i++) {
  if (tds[i].matches('.class')) {
    arr.push(i);
  }
}

Upvotes: 1

Related Questions