How to Sort List of Objects by Some Property

How to Sort a List T by a property in the object

The easiest way I can think of is to use Linq:

List<Order> SortedList = objListOrder.OrderBy(o=>o.OrderDate).ToList();

How to sort a list of objects based on an attribute of the objects?

# To sort the list in place...
ut.sort(key=lambda x: x.count, reverse=True)

# To return a new list, use the sorted() built-in function...
newlist = sorted(ut, key=lambda x: x.count, reverse=True)

More on sorting by keys.

How to sort list of objects with a property of another object in Java?

You can use Java 8 lambdas to create a mapping between a referenceName and its index in the Protocol sorted list:

public class Protocol {
final String referenceName;

public String getReferenceName() {
return referenceName;
}

// other stuff
}

public class Sensor {
final String referenceName;

public String getReferenceName() {
return referenceName;
}

// other stuff
}

final List<Protocol> protocols = getProtocols();
final List<Sensor> sensors = getSensors();

// TODO : sort protocols here

// create a mapping between a referenceName and its index in protocols
final Map<String, Integer> referenceNameIndexesMap = IntStream.range(0, protocols.size()).mapToObj(i -> i)
.collect(Collectors.toMap(i -> protocols.get(i).getReferenceName(), i -> i));

// sort sensors using this mapping
sensors.sort(Comparator.comparing(s -> referenceNameIndexesMap.get(s.getReferenceName())));

// sensors is now sorted in the same order of referenceName as protocols

Sort array of objects by string property value

It's easy enough to write your own comparison function:

function compare( a, b ) {
if ( a.last_nom < b.last_nom ){
return -1;
}
if ( a.last_nom > b.last_nom ){
return 1;
}
return 0;
}

objs.sort( compare );

Or inline (c/o Marco Demaio):

objs.sort((a,b) => (a.last_nom > b.last_nom) ? 1 : ((b.last_nom > a.last_nom) ? -1 : 0))

Or simplified for numeric (c/o Andre Figueiredo):

objs.sort((a,b) => a.last_nom - b.last_nom); // b - a for reverse sort

Sort a list of objects by the value of a property

Use OrderBy of Linq function. See http://msdn.microsoft.com/en-us/library/bb534966.aspx

cities.OrderBy(x => x.population);

Sorting object property by values

Move them to an array, sort that array, and then use that array for your purposes. Here's a solution:

let maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
let sortable = [];
for (var vehicle in maxSpeed) {
sortable.push([vehicle, maxSpeed[vehicle]]);
}

sortable.sort(function(a, b) {
return a[1] - b[1];
});

// [["bike", 60], ["motorbike", 200], ["car", 300],
// ["helicopter", 400], ["airplane", 1000], ["rocket", 28800]]

Once you have the array, you could rebuild the object from the array in the order you like, thus achieving exactly what you set out to do. That would work in all the browsers I know of, but it would be dependent on an implementation quirk, and could break at any time. You should never make assumptions about the order of elements in a JavaScript object.

let objSorted = {}
sortable.forEach(function(item){
objSorted[item[0]]=item[1]
})

In ES8, you can use Object.entries() to convert the object into an array:

const maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};

const sortable = Object.entries(maxSpeed)
.sort(([,a],[,b]) => a-b)
.reduce((r, [k, v]) => ({ ...r, [k]: v }), {});

console.log(sortable);

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));

Sorting List of Objects by long property

Look at the definition of Long#compare :

public static int compare(long x, long y) {
return (x < y) ? -1 : ((x == y) ? 0 : 1);
}

Similary, you simply can return 1 if the value greater than the other value, 0 if equals and -1 if less than:

Collections.sort(priceList, new Comparator<MyObject>() {
@Override
public int compare(MyObject o1, MyObject o2) {
return (o1.getPrice() < o2.getPrice()) ? -1 : ((o1.getPrice() == o2.getPrice()) ? 0 :1 );
});

Sort a list of objects in Flutter (Dart) by property value

You can pass a comparison function to List.sort.

someObjects.sort((a, b) => a.someProperty.compareTo(b.someProperty));


Related Topics



Leave a reply



Submit