Sortby Javascript Function Guide with Examples

In this article, we will guide you through the Sortby Javascript function and how it can be utilized to sort data effectively.

But before that, let’s understand first what is Javascript.

What is Javascript?

JavaScript is a programming language used for web development, allowing developers to create interactive and dynamic elements on websites.

It is supported by all modern browsers and can be used for both client-side and server-side applications.

Now, we will focus on one of its functions sortby().

What is javascript sortby function?

The _sortBy function is used to sort an array of objects based on a specific property or a custom iterator function.

It returns a new array with the elements sorted in ascending order.

Additionally, the sortBy Javascript function is part of the Underscore.js library. Underscore.js is a utility library for JavaScript that provides many helpful functions for working with arrays, collections, and objects.

Here is the syntax of this function:

_.sortBy(list, iteratee, [context])

The parameters used in the syntax are:

  • list: This is the array or collection of objects that you want to sort.
  • iteratee: It can be either a string representing the property to sort by or a function that determines the value to use for sorting.
  • context: It specifies the context or “this” value to be used when executing the iteratee function.

Examples of array sortby javascript

Here are a few examples of how you can use the _sortBy function with different variations of the iteratee parameter:

Example 1: Sorting an array of numbers

const _ = require('underscore');

const numbers = [5, 1, 10, 3];

// Sort the numbers array in ascending order using _sortBy
const sortedNumbers = _.sortBy(numbers);

console.log('Sorted Numbers:', sortedNumbers);

Output:

Sorted Numbers: [1, 3, 5, 10]

In this instance, we possess an array of numbers known as “numbers.”

By employing the _sortBy function without explicitly indicating an iteratee, the numbers will be arranged in their default order, which happens to be ascending.

Subsequently, the sorted collection of numbers is displayed on the console.

Example 2: Sorting an array of strings by length

const _ = require('underscore');

const strings = ['apple', 'banana', 'pear', 'grape'];

// Sort the strings array by length in ascending order using _sortBy
const sortedStrings = _.sortBy(strings, (str) => str.length);

console.log('Sorted Strings:', sortedStrings);

Output:

Sorted Strings: ["pear", "grape", "apple", "banana"]

In this example, we have an array of strings (strings).

We use the _sortBy function with a custom iteratee function that returns the length of each string. This will sort the strings based on their length in ascending order.

The sorted array is then printed to the console.

Example 3: Sorting an array of objects by a numeric property

const _ = require('underscore');

const products = [
  { name: 'speaker', price: 50 },
  { name: 'mic', price: 30 },
  { name: 'Monitor', price: 200 }
];

// Sort the products array by price in ascending order using _sortBy
const sortedProducts = _.sortBy(products, 'price');

console.log('Sorted Products:', sortedProducts);

Output:

Sorted Products: [
  { name: 'mic', price: 30 },
  { name: 'spesker', price: 50 },
  { name: 'Monitor', price: 200 }
]

In this specific case, we have an array of “products,” wherein each object represents a distinct product containing a name and price.

We employ the _sortBy function, explicitly indicating the price property as the iteratee.

This action will arrange the objects based on their prices in ascending order. Ultimately, the sorted array is displayed on the console for observation.

Importance of js sortby

The _sortBy function from Underscore.js provides several important benefits and use cases:

📌 Sorting flexibility

The function allows you to sort arrays of objects or values based on various criteria.

📌 Code simplicity and readability

By using the _sortBy function, you can write concise and readable code for sorting arrays.

📌 Non-destructive operation

The _sortBy function returns a new sorted array, leaving the original array unchanged.

📌 Compatibility and cross-platform support

Underscore.js is a widely used utility library with broad compatibility across different JavaScript environments.

📌 Enhanced productivity

The availability of utility functions like _sortBy in Underscore.js helps improve developer productivity by providing ready-to-use solutions for common array manipulation tasks.

Overall, the _sortBy function simplifies the process of sorting arrays in JavaScript, offering flexibility, improved code readability, and compatibility across different environments.

It is a valuable tool for developers working with arrays and seeking efficient and reliable sorting functionality.

Common Challenges in _sortBy function

Here are the common challenges for the _sortBy function:

  • Incorrect sorting order
  • Unsupported data types
  • Performance issues with large arrays
  • Unexpected results with special values
  • Inconsistent behavior across environments.
  • Lack of stability
  • Compatibility with non-array structures

Anyway, you can also check this article How long does it take to learn Javascript while intending to learn Javascript language.

Conclusion

In conclusion, this SortBy JavaScript is a powerful tool for adding sorting functionality to webpages.

By leveraging its capabilities, developers can enhance the user experience and make data manipulation seamless for users.

So why wait? Start implementing SortBy JavaScript in your javascript projects today and see the difference it can make!

I think that’s all for this function. We hoped you’ve learned in this article.

Until next time! 😊

Frequently Asked Questions

Is JavaScript still worth learning in 2026?
Yes. JavaScript runs on 98% of websites for the front-end, dominates the back-end via Node.js, powers mobile apps through React Native, builds desktop tools through Electron, and is the scripting layer for most AI tooling (LangChain.js, OpenAI SDK, Vercel AI). Whether you target web, mobile, AI, or full-stack capstones, JavaScript is the broadest single language you can learn.
What is the difference between var, let, and const?
var is function-scoped, hoisted to the top of its scope, and can be redeclared, which leads to bugs in modern code. let is block-scoped (only visible inside the nearest {}) and can be reassigned. const is block-scoped and cannot be reassigned, although object contents can still mutate. Default to const for everything, switch to let only when you actually need to reassign, and avoid var in any code written after 2017.
Which JavaScript version should I target in 2026?
Target ES2020 (ES11) as the safe baseline because every modern browser and Node.js 14+ supports it fully. ES2022 adds useful features like top-level await, private class fields with the # prefix, and the .at() array method. If you are writing for older browsers (IE11 or older Android WebViews), transpile down with Babel or use a build tool like Vite, esbuild, or webpack.
What is the best free editor for JavaScript?
Visual Studio Code is the industry standard, free, with built-in IntelliSense, debugger, terminal, Git, and a huge extension marketplace (ESLint, Prettier, GitHub Copilot, Tailwind). Install the JavaScript and TypeScript Nightly extension for the latest language features. JetBrains WebStorm is more powerful and free for students with a verified .edu email. For quick scratchpad work, the Chrome DevTools Sources panel includes a workspace and breakpoint debugger.
How do I run JavaScript locally vs in the browser?
In the browser: open DevTools with F12 (or right-click then Inspect), go to the Console tab, type or paste your code, press Enter. For HTML pages, add a script tag pointing to your .js file. Locally with Node.js: download Node from nodejs.org (LTS version), then run node script.js in your terminal from the file folder. Use the same Node setup for backend capstones, API integrations, and scripts that do not need a browser.
What can I build with JavaScript for my BSIT capstone?
Common BSIT capstones in JavaScript: full-stack web apps using React or Vue on the front-end with Node.js and Express on the back-end (MongoDB or MySQL for the database), real-time chat or notification systems using Socket.io, single-page dashboards with Chart.js or D3.js, cross-platform mobile apps with React Native, AI-powered chatbots using OpenAI SDK and LangChain.js, and Chrome extensions for productivity tools. Add Tailwind CSS for the UI and Vercel or Netlify for free deployment.
Glay Eliver

Programmer & Technical Writer at PIES IT Solution

Glay Eliver is a programmer and writer at PIES IT Solution, author of over 600 tutorials at itsourcecode.com. Specializes in JavaScript tutorials, Microsoft Office how-tos (Excel, Word, PowerPoint), and Python error debugging covering ImportError, TypeError, AttributeError, ModuleNotFoundError, and JavaScript ReferenceError. Authored several of the site’s highest-traffic Excel and MS Office reference articles.

Expertise: JavaScript · MS Excel · MS Word · MS PowerPoint · Python · Python ImportError · Python TypeError · Python AttributeError · ModuleNotFoundError · JavaScript ReferenceError · Pygame  · View all posts by Glay Eliver →

Leave a Comment