1

Hi I am wanting to sort a list of links to match an array order:

List: 

<a href="" data-value="10">10</a>
<a href="" data-value="6">6</a>
<a href="" data-value="8">8</a>
...
<a href="" data-value="m">M</a>
<a href="" data-value="s">S</a>

Array for Ordering:

['6', '8', '10', '12', '14', 'xs', 's', 'm', 'l', 'xl', 'xxl']

I am using the following which sorts the text options fine, but not the numerical ones:

(function () {
    var order = ['6', '8', '10', '12', '14', 'xs', 's', 'm', 'l', 'xl', 'xxl'];
    var $wrapper = $('.size-filter');
    $wrapper.find('a').sort(function (a, b) {
      var aSize = $(a).data('value'), bSize = $(b).data('value');
      return order.indexOf(aSize) - order.indexOf(bSize);
    }).appendTo($wrapper);
  })();

How can I adjust this sorting function or rewrite it so it sorts both text and numerical size options?

4
  • How should the sorted array look like? Commented May 6, 2019 at 0:46
  • Is it guaranteed that there's only one link per data-value or can there be multiple? If the latter, what should determine the secondary sorting? Commented May 6, 2019 at 0:53
  • @Phil yes there is only ever one link per value Commented May 6, 2019 at 0:53
  • @Pedro cool, just making sure my answer wouldn't blow up your app 🙂 Commented May 6, 2019 at 0:54

1 Answer 1

1

Store the links in a Map, keyed by their data-value attribute, then map the order array to the links

const links = [...document.querySelectorAll('a[data-value]')].reduce((map, link) =>
    map.set(link.dataset.value, link), new Map())

const orderedLinks = order.filter(k => links.has(k)).map(k => links.get(k))

You can then use jQuery to append these links to another element

$('some-element-selector').append(orderedLinks)

Note that I've filtered the order array to one where links actually exist.

Sign up to request clarification or add additional context in comments.

2 Comments

Works perfect, only change I made was to display the orderedLinks back in the page. Thanks for your help!
@Pedro I just added that to my answer but from the code in your question, I figured you already knew how to do that

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.