Sort Array of Objects by Two Properties

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

Sort array of objects by multiple properties of string type

The test should be (assuming your date format is dd/mm/yyyy)

if (a.name > b.name) return 1;
if (a.name < b.name) return -1;
let [a_dd, a_mm, a_yy] = a.joindate.split("/");
let [b_dd, b_mm, b_yy] = b.joindate.split("/");
if (a_yy !== b_yy) return a_yy - b_yy;
if (a_mm !== b_mm) return a_mm - b_mm;
if (a_dd !== b_dd) return a_dd - b_dd;
return 0;

Javascript - Sort Array of objects by 2 Properties

You could use a chained approach for a specified order of keys and their sort order.

The array is sorted by the properties

  • resHP, ascending and
  • resFlow, descending.

It works with calculating the delta and this reflects the relation of the two objects. If the value is zero, then the two values are equal and the next delta is calculated and returned.





var array = [{ resVal: "25FA15", resFlow: 49, resName: "Rendimiento Tri-Seal Completo", resPhoto: "Tri-Sealseries.png", resHP: 1.5 }, { resVal: "25FA2", resFlow: 52, resName: "Rendimiento Tri-Seal Completo", resPhoto: "Tri-Sealseries.png", resHP: 2 }, { resVal: "45FA2", resFlow: 53, resName: "Rendimiento Hi-Cap Completo", resPhoto: "HighCapseries.png", resHP: 2 }, { resVal: "35FA2", resFlow: 59, resName: "Rendimiento Hi-Cap Completo", resPhoto: "HighCapseries.png", resHP: 2 }];


array.sort(function (a, b) {

return a.resHP - b.resHP || b.resFlow - a.resFlow;

});


console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

PHP sort array of objects by two properties

Why the extra level of indirection and making things more confusing? Why not usort directly with usort($objectArray, "sortObjects"); using a sortObjects($a,$b) function that does what any comparator does: return negative/0/positive numbers based on the input?

If the tabs differ, return their comparison, if they're the same, return the order comparison; done.

$array = array(
(object)array(
'tab_option_name_selector' => 2,
'fieldtype' => 'notes',
'order' => 12
),
(object)array(
'tab_option_name_selector' => 2,
'fieldtype' => 'notes',
'order' => 8
),
(object)array(
'tab_option_name_selector' => 1,
'order' => 2,
'fieldtype' => 'selectbox'
),
(object)array(
'tab_option_name_selector' => 2,
'order' => 3,
'fieldtype' => 'selectbox'
)
);

function compareTabAndOrder($a, $b) {
// compare the tab option value
$diff = $a->tab_option_name_selector - $b->tab_option_name_selector;
// and return it. Unless it's zero, then compare order, instead.
return ($diff !== 0) ? $diff : $a->order - $b->order;
}

usort($array, "compareTabAndOrder");
print_r($array);

Sorting an array of objects by multiple properties with additional constraints

add one line in your code

if(a.due === null && b.due === null){
return sortByName(a,b)
}

function sortItems(a, b) {
const sortByName = (a, b) => {
const lc = x => x.name.toLowerCase();
return lc(a).localeCompare(lc(b));
}

const sortByDueDate = (a, b) => {
const time = x => x.due.getTime();
if(a.due === null && b.due === null){
return sortByName(a,b)
}
if (b.due === null)
return -1;

if (a.due === null)
return 1;

return time(a) - time(b);
}

return sortByDueDate(a, b) || sortByName(a, b);
}

const items = [
{name: 'AItem', due: new Date(2021, 8, 26)},
{name: 'WItem', due: null},
{name: 'TItem', due: new Date(2021, 7, 26)},
{name: 'CItem', due: new Date(2021, 7, 26)},
{name: 'ZItem', due: null},
{name: 'AItem', due: null},
{name: 'KItem', due: null},
{name: 'OItem', due: new Date(2021, 1, 11)},

];

console.log(items.sort(sortItems));

Sort an array of objects(with multiple properties) in a specified order of Keys with JavaScript

Rather than resorting the original data, you can map it to a new sorted array by indexing it with every element in your sortOrder in order. Something like this:

let result = sortOrder.map(key => sheetCells[0][key]);

While that's a working version of your solution, based on the data structure in your example, this may be closer to what you're looking for:

let result = sheetCells[0].map(cell => sortOrder.map(key => cell[key]));

Sort array of objects by two properties

Yes there is a very simple way using the Array.sort()

Code:

var sorted = array.sorted({ (s1, s2) -> Bool in
if s1.isPriority && !s2.isPriority {
return true //this will return true: s1 is priority, s2 is not
}
if !s1.isPriority && s2.isPriority {
return false //this will return false: s2 is priority, s1 is not
}
if s1.isPriority == s2.isPriority {
return s1.ordering < s2.ordering //if both save the same priority, then return depending on the ordering value
}
return false
})

The sorted array:

true - 10
true - 10
true - 12
true - 12
true - 19
true - 29
false - 16
false - 17
false - 17
false - 17
false - 18

Another a bit shorter solution:

let sorted = array.sorted { t1, t2 in 
if t1.isPriority == t2.isPriority {
return t1.ordering < t2.ordering
}
return t1.isPriority && !t2.isPriority
}

How to reduce an array of objects with two properties into two arrays, one for each property?

You can do

const canais = channel.map(item => item.canais)
const topicos = channel.map(item => item.topicos)


Related Topics



Leave a reply



Submit