Underscore: sortBy() based on multiple attributes

Active3 hr before
Viewed126 times

7 Answers


Thanks for contributing an answer to Stack Overflow!, Stack Overflow for Teams Where developers & technologists share private knowledge with coworkers ,Simple Example from http://janetriley.net/2014/12/sort-on-multiple-keys-with-underscores-sortby.html (courtesy of @MikeDevenney), Stack Overflow Public questions & answers

sortBy says that it is a stable sort algorithm so you should be able to sort by your second property first, then sort again by your first property, like this:

var sortedArray = _(patients).chain().sortBy(function(patient) {
   return patient[0].name;
}).sortBy(function(patient) {
   return patient[0].roomNumber;
load more v

Alternatively, this could trivially be implemented as the generalized case of the existing _.sortBy() . (excepting both the current _.sortyBy input for sorting on a single property as well as an array for multi-property support),Sorting on multiple properties, e.g: when sorting on the first property results in a 'draw' we use the second property for sorting, etc.,Currently you can already use _.sortBy to sort on multiple properties, as long as you are using strings.,I have a need for something like this as well and a single value doesn't really solve the problem well.

_(people).sortBy(function(p) {
   return [p.lastName, p.age];
load more v

Using Math.cos() function: Passing a list of numbers and do operations like taking ‘cos()’ of the numbers and then comparing them to sort the array. In the same manner apply all the “math’ function like tan(), sin(), cot() etc to sort the array.,Return values: It returns a sorted array which is being sorted according to the function passed.,Parameters: This function accepts three parameters as mentioned above and described below:,The Underscore.js is a JavaScript library that provides a lot of useful functions that helps in the programming in a big way like the map, filter, invoke etc even without using any built-in objects.The _.sortBy() function is used to sort all the elements of the list in ascending order according to the function given to it as a parameter. Passing the array with a function which returns the number and it will sort the array in ascending order and return an array. The array can be both of numeric values and string values.


_.sortBy(list, iteratee, [context])
load more v

The sortBy function may now also be passed the string name of a property to use as the sort order on each object. , keys_.keys(object) Retrieve all the names of the object's own enumerable properties. , The times function now returns the mapped array of iterator results. , allKeys_.allKeys(object) Retrieve all the names of object's own and inherited properties.

each_.each(list, iteratee, [context]) Alias: forEach
Iterates over a list of elements, yielding each in turn to an iteratee function. The iteratee is bound to the context object, if one is passed. Each invocation of iteratee is called with three arguments: (element, index, list). If list is a JavaScript object, iteratee's arguments will be (value, key, list). Returns the list for chaining.

_.each([1, 2, 3], alert); => alerts each number in turn...
      one: 1,
      two: 2,
      three: 3
   }, alert); => alerts each number value in turn...
load more v

  To sort by multiple fields, you can do like:,JavaScript native method sort() is commonly used to in-place sort elements of an array. The sort() method optionally accepts a comparison function, which defines the sort order. If x and y are two elements being compared with comparison function comp, then if :,This post will discuss how to sort an array of objects in JavaScript.,That’s all about sorting an array of objects in JavaScript.

load more v

This Underscore JS tutorial will focus on the Underscore sortBy function, which works with both JavaScript objects and JavaScript arrays. Like the other tutorials that offer code examples we can run, so too will we offer several examples of the sortBy() function here. We’ll look at sorting an integer array, sorting string arrays, sorting by the property name of an array of objects, as well as setting up custom sort criteria. Let’s have a look at the Underscore sortBy() function now.,This wraps up another fun tutorial for using the sortBy function in the Underscore JavaScript library. We can see the power and flexibility we have with sortBy when we need to set custom sort criteria to get the results we want whether working with integer arrays, strings, arrays of objects, or various other types of data.,Refactor The Laravel Regex Tool To Use Repositories and Dependency Injection,77 Helpful Technet Articles For Advanced Microsoft System Administrators

This first example has a simple integer array set up with the values of 1 through 10 assigned to the values variable. In JavaScript, arrays already have a built in sort function, so why the need for an Underscore sortBy function? Well, the sortBy function has just a bit more granularity associated with it. This first example makes use of an oddSorter function which we can pass as the second argument to the sortBy() function to customize how sorting happens. What we do in this case is to sort the odd numbers first, followed by the even numbers. The sortBy() function offers just a bit more control over how you sort.

var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];

var oddSorter = function(value) {
   return value % 2 === 0;

var sortedValues = _.sortBy(values, oddSorter);

log('Sort odd numbers first:', '#sortbyexampleoneunderscore');
log(sortedValues, '#sortbyexampleoneunderscore');
load more v

Tôi đang cố gắng sắp xếp một mảng với các đối tượng dựa trên nhiều thuộc tính. Tức là nếu thuộc tính thứ nhất giống nhau giữa hai đối tượng thì nên sử dụng thuộc tính thứ hai để comapare hai đối tượng. Ví dụ, hãy xem xét các mảng sau:

var patients = [
      name: 'John',
      roomNumber: 1,
      bedNumber: 1
      name: 'Lisa',
      roomNumber: 1,
      bedNumber: 2
      name: 'Chris',
      roomNumber: 2,
      bedNumber: 1
      name: 'Omar',
      roomNumber: 3,
      bedNumber: 1

Sắp xếp chúng theo roomNumberthuộc tính tôi sẽ sử dụng đoạn mã sau:

var sortedArray = _.sortBy(patients, function(patient) {
   return patient[0].roomNumber;
load more v

Other "underscore-multiple" queries related to "Underscore: sortBy() based on multiple attributes"