Categories
JavaScript Answers

How to use JavaScript to sort contents of select element?

Spread the love

Sometimes, we want to use JavaScript to sort contents of select element.

In this article, we’ll look at how to use JavaScript to sort contents of select element.

How to use JavaScript to sort contents of select element?

To use JavaScript to sort contents of select element, we use the sort method.

For instance, we write

const optionNodes = Array.from(selectNode.children);
const comparator = new Intl.Collator(lang.slice(0, 2)).compare;

const sorted = optionNodes.sort((a, b) =>
  comparator(a.textContent, b.textContent)
);

to call Array.from to convert the node list with select element’s child elements into an array.

Then we get the compare function from the Intl.Collator constructor.

And then we call sort with a callback that calls comparator to return an array sorted by the child element’s text content.

Conclusion

To use JavaScript to sort contents of select element, we use the sort method.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *