Sorting Arrays Numerically by Object Property Value

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 arrays numerically by object property value

Use Array.prototype.sort(), eg

myArray.sort((a, b) => a.distance - b.distance)

The sort() method accepts a comparator function. This function accepts two arguments (both presumably of the same type) and it's job is to determine which of the two comes first.

It does this by returning an integer

  • Negative (less-than zero): The first argument comes first
  • Positive (greater-than zero): The second argument comes first
  • Zero: The arguments are considered equal for sorting

When you're dealing with numeric values, the simplest solution is to subtract the second value from the first which will produce an ascending order result.

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 an array of objects based on a numeric key given as String

Use Arrays.sort()

var arr = [{"id":"165","name":"a"},{"id":"236","name":"c"},{"id":"376","name":"b"},{"id":"253","name":"f"},{"id":"235","name":"e"},{"id":"24","name":"d"},{"id":"26","name":"d"}];arr.sort((a,b)=> Number(a.id) - Number(b.id));console.log(arr);

Javascript sort an array of objects based on numeric key

But that is angular so normal Javascript it doesn't work.

Simply you can use JavaScript sort function. It will work in Angular(TypeScript) also.

Note: When sorting numbers, you can simply use the compact comparison:

myArray.sort((n1,n2) => n1 - n2);

var data = [ {   title: 'Shirt',   position: 3 }, {   title: 'Ball',   position: 1, }];
data.sort(function(a, b) { return a.position- b.position;})
console.log(data);

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 based on a property value (int)

You can use Array.prototype.sort() and define a compare function:

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

list.sort(compareIndexFound);

Simpler/Concise version of above compare function:

function compareIndexFound(a, b) {
return a.indexFound - b.indexFound;
}

Using ES6:

list.sort((a, b) => a.indexFound - b.indexFound);

You can define your own sortBy function:

function sortBy(arr, prop) {
return arr.sort((a, b) => a[prop] - b[prop]);
}

sortBy(list, 'indexFound');

Sorting array based on a property value

Try this:

let arr = [
{id: 23634, pollId: 6907, name: "B", type: "PollOption", totalAmountRaised: 341,},
{id: 23635, pollId: 6907, name: "A", type: "PollOption", totalAmountRaised: 636,},
{id: 23641, pollId: 6907, name: "C", type: "PollOption", totalAmountRaised: 246,},
{id: 23642, pollId: 6907, name: "D", type: "PollOption", totalAmountRaised: 1092,},
{id: 23643, pollId: 6907, name: "E", type: "PollOption", totalAmountRaised: 0},
]

let sorted = arr.sort((a, b) => b.totalAmountRaised - a.totalAmountRaised)
console.log(sorted)


Related Topics



Leave a reply



Submit