Sort Array of Objects

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

How to sort an array of objects in Java?

You have two ways to do that, both use the Arrays utility class

  1. Implement a Comparator and pass your array along with the comparator to the sort method which take it as second parameter.
  2. Implement the Comparable interface in the class your objects are from and pass your array to the sort method which takes only one parameter.

Example

class Book implements Comparable<Book> {
public String name, id, author, publisher;
public Book(String name, String id, String author, String publisher) {
this.name = name;
this.id = id;
this.author = author;
this.publisher = publisher;
}
public String toString() {
return ("(" + name + ", " + id + ", " + author + ", " + publisher + ")");
}
@Override
public int compareTo(Book o) {
// usually toString should not be used,
// instead one of the attributes or more in a comparator chain
return toString().compareTo(o.toString());
}
}

@Test
public void sortBooks() {
Book[] books = {
new Book("foo", "1", "author1", "pub1"),
new Book("bar", "2", "author2", "pub2")
};

// 1. sort using Comparable
Arrays.sort(books);
System.out.println(Arrays.asList(books));

// 2. sort using comparator: sort by id
Arrays.sort(books, new Comparator<Book>() {
@Override
public int compare(Book o1, Book o2) {
return o1.id.compareTo(o2.id);
}
});
System.out.println(Arrays.asList(books));
}

Output

[(bar, 2, author2, pub2), (foo, 1, author1, pub1)]
[(foo, 1, author1, pub1), (bar, 2, author2, pub2)]

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

Sort Array of Objects based on position of value in another Array of Strings

You can loop the correct_order array and filter the unsorted array by using the js filter function. If filter match push to an new array.

const UNSORTED = [{Type: 'Grass', Value: 'Wet'}, {Type: 'Sand', Value: 'Dry'}, {Type: 'Animal', Value: 'Dog'}];

const CORRECT_ORDER = ['Animal','Plant','Sand','Grass'];

let sorted = []
CORRECT_ORDER.forEach(k => {
let n = UNSORTED.filter(obj => {
return obj.Type === k
})
if (n.length > 0) {
sorted.push(n);
}

})

console.log(sorted);

Javascript sort array of objects using array of priority

You could do it using Array.prototype.sort() method with an ordering array.

const eventList = [
{
eventName: 'abc',
status: 'completed',
},
{
eventName: 'def',
status: 'live',
},
{
eventName: 'ghi',
status: 'live',
},
{
eventName: 'jkl',
status: 'upcoming',
},
];

const order = ['live', 'upcoming', 'completed'];
eventList.sort((x, y) => order.indexOf(x.status) - order.indexOf(y.status));
console.log(eventList);

Javascript sort an array of objects by field and sorting direction

If you want to sort by string in alphabetical order, you can so something like this:

const arr = [{
name: 'John',
age: 20,
},
{
name: 'Mark',
age: 30,
},
{
name: 'Luke',
age: 19
}
]
const order = {
field: 'name',
asc: true,
}

orderedList = arr.sort((a, b) => {
if (order.asc) {
if (a[order.field] > b[order.field]) {
return 1
} else if (a[order.field] < b[order.field]) {
return -1
} else {
return 0
}
}
});
console.log(orderedList)

How to sort array of objects according to epoch time in JavaScript

You can directly subtract the times in the sort callback.

data.sort((a, b)=>b.transactionTime - a.transactionTime);

How to sort array by object property with multiple conditions in Javascript

If the direction is the same in both compared items, you can conditionally choose the evaluation of the other columns based on the direction:

queues.sort((a,b) =>
(a.direction=="CALL_DOWN") - (b.direction=="CALL_DOWN") ||
(a.direction == "CALL_DOWN"
? b.floor - a.floor
: a.floor - b.floor)
);


Related Topics



Leave a reply



Submit