Sorting an Array by Two Values

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 2 values

Here is an example using array.sort:

var arr = [    {id: 1, date: "2015-01-18T15:00:00+01:00"},     {id: 1, date: "2015-01-18T14:30:00+01:00"},     {id: 2, date: "2015-01-18T10:00:00+01:00"},     {id: 1, date: "2015-01-18T16:00:00+01:00"},     {id: 3, date: "2015-01-18T14:15:00+01:00"},     {id: 2, date: "2015-01-18T14:00:00+01:00"}];
arr.sort(function(a,b){ if (a.id == b.id) return a.date.localeCompare(b.date); return a.id-b.id; });
// testfor (var i in arr) { console.log(arr[i]);}

Java 4 : Sorting an array by 2 values

Using Comparator interface, without Generics (<..>)

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.List;

public class CollectionSorter {

public static void main(String args[]) {
ClassTest obj1 = new ClassTest();
obj1.setCode("01");
obj1.setDate("2001-02-01");
ClassTest obj2 = new ClassTest();
obj2.setCode("01");
obj2.setDate("2001-01-01");
ClassTest obj3 = new ClassTest();
obj3.setCode("02");
obj3.setDate("2001-01-01");

List list = new ArrayList();
list.add(obj1);
list.add(obj2);
list.add(obj3);
System.out.println("Before sorting - " + list);
Collections.sort(list, new ClassTestComparator());
System.out.println("After sorting - " + list);
}

}

class ClassTest{
private String code; // "01", "02" or "03".
private String date; // 01/01/2001.

public String getCode() {
return code;
}

public void setCode(String code) {
this.code = code;
}

public String getDate() {
return date;
}

public void setDate(String date) {
this.date = date;
}

public String toString()
{
return "[code: " + code + ", date: " + date + "]";
}
}

class ClassTestComparator implements Comparator {

public int compare(Object o1, Object o2) {
ClassTest obj1 = (ClassTest) o1;
ClassTest obj2 = (ClassTest) o2;
int code1 = Integer.parseInt(obj1.getCode());
int code2 = Integer.parseInt(obj2.getCode());
int result = 0;
if(code1 > code2) {
result = 1;
}
if(code1 < code2) {
result = -1;
}
if (result != 0) {
return result;
}

// Sort by Date ("by the closest date of the current date")
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
Date date1 = null;
Date date2 = null;
try {
date1 = sdf.parse(obj1.getDate());
date2 = sdf.parse(obj2.getDate());
} catch(ParseException e) {
e.printStackTrace();
}
if(date1.compareTo(date2)>0){
result = 1;
}else if(date1.compareTo(date2)<0){
result = -1;
}else if(date1.compareTo(date2)==0){
result = 0;
}
return result;
}

}

Note: The code is tested in Java 1.4 version and works as expected

Sort array by two values

Use something like this:

yourArray.sort(function(a, b){
return a["gold"] == b["gold"] ? a["range"] - b["range"] : a["gold"] ? -1 : 1;
});

Or even this:

yourArray.sort(function(a, b){
return b["gold"] - a["gold"] || a["range"] - b["range"];
});

The second approach is really cool actually)) You can just use this pattern for any number of fields in your object, just order them by their importance. If some field should be sorted as ascending - than a["..."] - b["...], if as descending - than b["..."] - a["..."]

Sorting array based on multiple values of the same attribute in Javascript

You are on the right track with your sortByDate function, which is passed in to the .sort() method as the "CompareFunction".

The CompareFunction that you provide will be passed two parameters, which are by-convention called "a" and "b", and must provide an answer which denotes their relative position:

  • If 'a comes before b' or if 'a is less than b' then return an answer < 0.
  • If 'a comes after b' or if 'a is greater than b' then return an answer > 0.
  • If 'a and b are equal' then you can return the answer 0.

It is entirely up to you how the CompareFunction deals with those objects. You might only compare a single property, compare multiple properties, or even perform complex processing within your function (but don't).

For comparisons which are numeric in nature, you can arithmetically determine the answer.
E.g.

function sortNumbersInAscendingOrder(a, b) {
return a - b;
}

If a > b then a - b results in a positive answer, which states that 'a comes after b'.

Comparing strings is a bit different as the comparison operators return a boolean value. However, you don't actually need to provide all three variants of answer from your CompareFunction - you are allowed to favour one of your objects and say that it comes first even when they're the same. This allows you to sort strings simply using the ternary operator.
E.g.

function sortStringsAlphabeticalOrder(a, b) {
// Note: this is a case sensitive sort!
return (a <= b) ? -1 : 1;
}

As usual, the Mozilla docs provide an excellent technical answer:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

PHP sort array by two field values

array_multisort() is the correct function, you must have messed up somehow:

// Obtain a list of columns
foreach ($data as $key => $row) {
$return_fare[$key] = $row['return_fare'];
$one_way_fare[$key] = $row['one_way_fare'];
}

// Sort the data with volume descending, edition ascending
array_multisort($data, $return_fare, SORT_ASC, $one_way_fare, SORT_ASC);

If you take a look at the comments at PHP's manual page for array_multisort(), you can find a very helpful array_orderby() function which allows you to shorten the above to just this:

$sorted = array_orderby($data, 'return_fare', SORT_ASC, 'one_way_fare', SORT_ASC);

To avoid the looping use array_column() (as of PHP 5.5.0):

array_multisort(array_column($data, 'return_fare'),  SORT_ASC,
array_column($data, 'one_way_fare'), SORT_ASC,
$data);

Array sorting by two parameters

i think this is what you are after:

sourcearray.OrderBy(a=> a.sum).ThenBy(a => a.random)


Related Topics



Leave a reply



Submit