JavaScript Sort Function. Sort by First Then by Second

Javascript sort function. Sort by First then by Second

Expand your sort function to be like this;

function sortF(ob1,ob2) {
if (ob1.strength > ob2.strength) {
return 1;
} else if (ob1.strength < ob2.strength) {
return -1;
}

// Else go to the 2nd item
if (ob1.name < ob2.name) {
return -1;
} else if (ob1.name > ob2.name) {
return 1
} else { // nothing to split them
return 0;
}
}

A < and > comparison on strings is an alphabetic comparison.

Javascript: sort 2D array at first by second column desc, then by first column asc

Update/note: this is a great compact sorting function for your situation that also supports strings with non-ASCII characters. I would consider this to be an "improvement" to my answer, only at the cost of being less easy to understand except to someone who knows what is going on:

myarr.sort(
function(a,b) {
return b[1]-a[1] || a[0].localeCompare(b[0]);
}
);

Original suggested answer: This code will take the data you gave (randomized) and produce the output sorted as you desired.

myarr = [
['Dean', 17],
['John', 48],
['Ann', 36],
['Sean', 18],
['Bob', 36],
['Carl', 36]
];

myarr.sort(
function(a,b) {
if (a[1] == b[1])
return a[0] < b[0] ? -1 : 1;
return a[1] < b[1] ? 1 : -1;
}
);

alert(myarr);

Sort an array of arrays in JavaScript

You can pass a custom comparison function to Array.prototype.sort(), like so:

var sortedArray = array.sort(function(a, b) { return a - b; });

This would sort an array of integers in ascending order. The comparison function should return:

  • an integer that is less than 0 if you want a to appear before b
  • an integer that is greater than 0 if you want b to appear before a
  • 0 if a and b are the same

So, for this example you would want something like:

var sortedArray = array.sort(function(a, b) {
return b[0] - a[0];
});

If you wanted to sort on both elements of each sub-array (ie. sort by the first element descending, then if they are the same then sort by the second element descending), you could do this:

var sortedArray = array.sort(function(a, b) {
if (a[0] == b[0]) {
return a[1] - b[1];
}
return b[0] - a[0];
});

See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort for more info.

Javascript - sort array based on another array

One-Line answer.

itemsArray.sort(function(a, b){  
return sortingArr.indexOf(a) - sortingArr.indexOf(b);
});

Or even shorter:

itemsArray.sort((a, b) => sortingArr.indexOf(a) - sortingArr.indexOf(b));

javascript - sort by multiple criteria - first by another array and then by another property inside

You need to specify array as

var order =['c', 'y', 's'];

otherwise c, y and s needs to be variables.

Also, you need to compare the counter variables as well if codes are equal

data.sort(function(a,b){
if ( a.code == b.code )
{
return a.counter - b.counter;
}
else
{
return order.indexOf(a.code) - order.indexOf(b.code);
}
})

Sorting an array of objects by property values

Sort homes by price in ascending order:

homes.sort(function(a, b) {
return parseFloat(a.price) - parseFloat(b.price);
});

Or after ES6 version:

homes.sort((a, b) => parseFloat(a.price) - parseFloat(b.price));

Some documentation can be found here.

For descending order, you may use

homes.sort((a, b) => parseFloat(b.price) - parseFloat(a.price));

How to perform a JavaScript Sort() with a Then-By

myArray.sort(function(a,b){
if(a.Name>b.Name){return 1;}
else if(a.Name<b.Name){return -1;}
else{
if(a.Total>b.Total) return 1;
else if(a.Total<b.Total) return -1;
else return 0;
}
});

Minified version:

myArray.sort(function(a,b){return a.Name>b.Name?1:a.Name<b.Name?-1:a.Total>b.Total?1:a.Total<b.Total?-1:0});

javascript sort function Two fields (conditional)

Array#sort is based on repeatedly comparing two elements from the array. If both elements have non-zero groups, it's easy: First compare the groups, then (if they have the same group), compare the order. Similarly, if both elements are in group 0, just compare the order.

Where it gets tricky is if one element has a group of 0 and the other a non-zero group. In that case you can't directly compare them: To figure out which element should come first in the result array, you have to look at the lowest order among all elements that are in the non-zero group. This information is not directly available.

We can make it available by making a pass through the array up front and storing the lowest order of each non-zero group in an associative array (minOf in the code below).

The comparison function first checks whether both elements have a non-zero group (or both have a group of 0). In either case we can do a normal two-field comparison (group first, then order).

Otherwise we need to compare the order field of the element in group 0 with the minOf value of the non-zero group.

The ... || -1 and ... || 1 fallbacks provide a consistent ordering in the case where two elements have the same order, but one has group 0 and the other doesn't.

function sortGrouped(arr) {    let minOf = [];    for (const x of arr) {        if (x.group !== 0 && (minOf[x.group] === undefined || x.order < minOf[x.group])) {            minOf[x.group] = x.order;        }    }    return arr.sort((a, b) => {        if ((a.group === 0) === (b.group === 0)) {            return a.group - b.group || a.order - b.order;        }        return (            a.group === 0                ? a.order - minOf[b.group] || -1                : minOf[a.group] - b.order || 1        );    });}
const obj = [ {order:1, title:"Receipts", group:0}, {order:2, title:"Apples", group:1}, {order:7, title:"Costs", group:0}, {order:4, title:"Surplus", group:0}, {order:5, title:"Bananas", group:1}, {order:6, title:"Celery", group:2}, {order:8, title:"Documents", group:0}, {order:3, title:"Potatoes", group:2}];
const newObj = sortGrouped(obj); console.log(newObj);


Related Topics



Leave a reply



Submit