JAVASCRIPT
sort object by value javascript
const objSortedByVal = Object.fromEntries(
Object.entries(obj).sort(([, a], [, b]) => a - b)
)
sort object array javascript
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);
javascript sort object
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 28800
};
var 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]]
sort object array javascript
//using es6, simply:
data.sort((a, b) => a.city.localeCompare(b.city) || b.price - a.price);
js object sort
var maxSpeed = {
car: 300,
bike: 60,
motorbike: 200,
airplane: 1000,
helicopter: 400,
rocket: 8 * 60 * 60
};
var 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]]
sort() object values javascript
list.sort((a, b) => (a.color > b.color) ? 1 : (a.color === b.color) ? ((a.size > b.size) ? 1 : -1) : -1 )
js how to sort array by object value
// @ts-check
(function () {
const cars = [
{ type: 'Volvo', year: 2016 },
{ type: 'Saab', year: 2001 },
{ type: 'BMW', year: 2010 },
];
/**
* @param {object[]} arr
*/
function sortByValue(arr) {
arr.sort(function (
/** @type {{ year: number; }} */ a,
/** @type {{ year: number; }} */ b
) {
return a.year - b.year;
});
return arr;
}
console.log(sortByValue(cars)); // => [{ type: 'Saab', year: 2001 }, { type: 'BMW', year: 2010 },{ type: 'Volvo', year: 2016 }]
})();