Sort JavaScript Array by Two Numeric Fields

sort Javascript array by two numeric fields

grouperArray.sort(function (a, b) {
var aSize = a.gsize;
var bSize = b.gsize;
var aLow = a.glow;
var bLow = b.glow;
console.log(aLow + " | " + bLow);

if(aSize == bSize)
{
return (aLow < bLow) ? -1 : (aLow > bLow) ? 1 : 0;
}
else
{
return (aSize < bSize) ? -1 : 1;
}
});

How to sort an array of objects by multiple fields?

You could use a chained sorting approach by taking the delta of values until it reaches a value not equal to zero.

var data = [{ h_id: "3", city: "Dallas", state: "TX", zip: "75201", price: "162500" }, { h_id: "4", city: "Bevery Hills", state: "CA", zip: "90210", price: "319250" }, { h_id: "6", city: "Dallas", state: "TX", zip: "75000", price: "556699" }, { h_id: "5", city: "New York", state: "NY", zip: "00010", price: "962500" }];
data.sort(function (a, b) { return a.city.localeCompare(b.city) || b.price - a.price;});
console.log(data);
.as-console-wrapper { max-height: 100% !important; top: 0; }

JavaScript sort array by multiple (number) fields

You should design your sorting function accordingly:

items.sort(function(a, b) {
return a.sort1 - b.sort1 || a.sort2 - b.sort2;
});

(because || operator has lower precedence than - one, it's not necessary to use parenthesis here).

The logic is simple: if a.sort1 - b.sort1 expression evaluates to 0 (so these properties are equal), it will proceed with evaluating || expression - and return the result of a.sort2 - b.sort2.

As a sidenote, your items is actually a string literal, you have to JSON.parse to get an array:

const itemsStr = `[{    "sort1": 1,    "sort2": 3,    "name": "a"  },  {    "sort1": 1,    "sort2": 2,    "name": "b"  },  {    "sort1": 2,    "sort2": 1,    "name": "c"  }]`;const items = JSON.parse(itemsStr);items.sort((a, b) => a.sort1 - b.sort1 || a.sort2 - b.sort2);console.log(items);

Sort an array of objects by multiple fields

You may use this multi sort function from https://stackoverflow.com/a/22672370/3807365 - basically you just tell it which fields to sort by and you shall get a sorting method to pass to your Array.sort.

let objs = [{
name: 'Mark',
age: 31,
id: 3,
},
{
name: 'Anne',
age: 20,
id: 2,
},
{
name: 'James',
age: 40,
id: 4,
},
{
name: 'Jerry',
age: 30,
id: 1,
},
{
name: 'Lucy',
age: 30,
id: 5,
},
{
name: 'Mark',
age: 30,
id: 6,
},
]

function getSortMethod() {
var _args = Array.prototype.slice.call(arguments);
return function(a, b) {
for (var x in _args) {
var ax = a[_args[x].substring(1)];
var bx = b[_args[x].substring(1)];
var cx;

ax = typeof ax == "string" ? ax.toLowerCase() : ax / 1;
bx = typeof bx == "string" ? bx.toLowerCase() : bx / 1;

if (_args[x].substring(0, 1) == "-") {
cx = ax;
ax = bx;
bx = cx;
}
if (ax != bx) {
return ax < bx ? -1 : 1;
}
}
}
}

objs.sort(getSortMethod('+name', '+age'));
console.log(objs)
.as-console-wrapper {
max-height: 100% !important;
}

JS: Sorting array by multiple fields doesn't works

One approach could be encoding and weighting objects based on your condition. Take a look at this code:

var obj = [{ name: "B",  isActive: true,  createSheet: false,  centralBox: false },{ name: "A",  isActive: true,  createSheet: false,  centralBox: false },{ name: "B",  isActive: false,  createSheet: false,  centralBox: false },{ name: "B",  isActive: false,  createSheet: false,  centralBox: true },{ name: "B",  isActive: false,  createSheet: true,  centralBox: false },{ name: "B",  isActive: false,  createSheet: true,  centralBox: true }]
for (const o of obj){ let score = o.isActive === true ? 0 : 50 score += o.centralBox === true ? 0 : 20 score += o.createSheet === true ? 0 : 10 score += o.name.charCodeAt(0) o.score = score}obj.sort((a, b) => a.score - b.score)console.log(obj)

How do you sort an array on multiple columns?

If owner names differ, sort by them. Otherwise, use publication name for tiebreaker.

function mysortfunction(a, b) {

var o1 = a[3].toLowerCase();
var o2 = b[3].toLowerCase();

var p1 = a[1].toLowerCase();
var p2 = b[1].toLowerCase();

if (o1 < o2) return -1;
if (o1 > o2) return 1;
if (p1 < p2) return -1;
if (p1 > p2) return 1;
return 0;
}

How to sort an array of integers correctly

By default, the sort method sorts elements alphabetically. To sort numerically just add a new method which handles numeric sorts (sortNumber, shown below) -

var numArray = [140000, 104, 99];
numArray.sort(function(a, b) {
return a - b;
});

console.log(numArray);

I have to sort JavaScript array with more than one field combination and in that one field is combination of numbers & string

You could sort with an object for the order and sort then by grade or first_name.

const emps = [{ first_name: 'PQR', grade: 'K' }, { first_name: 'ABC', grade: 'K' }, { first_name: 'LMN', grade: '4' }, { first_name: 'CDE', grade: '2' }, { first_name: 'JKP', grade: '12' }, { first_name: 'ASD', grade: 'Others' }],
order = { K: -1, Others: 1, default: 0 };

emps.sort((a, b) =>
(order[a.grade] || order.default) - (order[b.grade] || order.default) ||
a.grade - b.grade ||
a.first_name.localeCompare(b.first_name)
);

console.log(emps);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Sort array of objects by multiple properties of string type

The test should be (assuming your date format is dd/mm/yyyy)

if (a.name > b.name) return 1;
if (a.name < b.name) return -1;
let [a_dd, a_mm, a_yy] = a.joindate.split("/");
let [b_dd, b_mm, b_yy] = b.joindate.split("/");
if (a_yy !== b_yy) return a_yy - b_yy;
if (a_mm !== b_mm) return a_mm - b_mm;
if (a_dd !== b_dd) return a_dd - b_dd;
return 0;


Related Topics



Leave a reply



Submit