Lena
Lena

Reputation: 39

combining two filter functions but specific order

I'd like to combine two different filter functions but I need the returned data in a specific order. here's my code:

html

<tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
    <td>d</td>
    <td>e</td>
    <td>f</td>
</tr>

js

filter1 = $('tr td').filter(function(index) {
    return index > 2
});

filter2 = $('tr td').filter(function(index) {
    return index <= 2
});

merge = $.merge(filter1, filter2);

expected output

from fitler1
<li>c</li>
<li>d</li>
<li>e</li>
<li>f</li>
from filter2
<li>a</li>
<li>b</li>

I've already tried to use return index > 2 || index <= 2 but this way I obviously get the same order as in HTML code. Is it even possible to use one filter to achieve what I'm after?

Upvotes: 0

Views: 56

Answers (2)

charlietfl
charlietfl

Reputation: 171679

You can also simplify those filters with :lt() and :gt() selectors

const $cells = $('td');

$.merge($cells.filter(':gt(1)'), $cells.filter(':lt(2)'))
         .each((i,el)=>  $('ul').append(`<li>${$(el).text()}</li>`))
                      
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table border=1>
  <tr>
    <td>a</td>
    <td>b</td>
    <td>c</td>
    <td>d</td>
    <td>e</td>
    <td>f</td>
  </tr>
</table>

<ul></ul>

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370689

You can slice the collection of <td>s to put them in the desired order:

const tds = $('td');
const ordered = $.merge(tds.slice(2), tds.slice(0, 2));
console.log(ordered);

const tds = $('td');
const ordered = $.merge(tds.slice(2), tds.slice(0, 2));
console.log(ordered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td>a</td>
  <td>b</td>
  <td>c</td>
  <td>d</td>
  <td>e</td>
  <td>f</td>
</tr>
</table>
Another option, using nth-child selectors:

const ordered = $.merge(
  $('td:nth-child(2) ~ *'),
  $('td:nth-child(-n + 2)')
);
console.log(ordered);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td>a</td>
  <td>b</td>
  <td>c</td>
  <td>d</td>
  <td>e</td>
  <td>f</td>
</tr>
</table>

Upvotes: 2

Related Questions