Using a Double Sort on an Array of Objects

preview_player
Показать описание
In this tutorial we are going to tackle another JavaScript problem. And in this problem I want to use the sort method of arrays. So we are going to look at how we can sort objects in an array, but we will be using a primary sort and a secondary sort.

Would you like to help keep this channel going?

Tutorials referred to in this video:

For more resources on JavaScript:

#javascript #AllThingsJavaScriptLLC
Рекомендации по теме
Комментарии
Автор

THE MASTER
🌟 🌟 - & - 🌟 🌟
A Masterpiece

gmkhussain
Автор

Here's my solution. Instead of limiting it to primary and secondary sort, my solution allows infinite sort. I create a comparatorGenerator function that takes the property names we want to compare with, the order in which they are inserted determines their sorting order. That function returns the comparator function we need to pass to the sort method.

function
return function(objectA, objectB) {
const a = objectA[prop[0]];
const b = objectB[prop[0]];
if (a < b) return 1;
if (a > b) return -1;
if (prop.length > 1) return comparatorGenerator(...prop.slice(1))(objectA, objectB);
return 0;
}
}

so if you want the sorting order to be fName, lName, age, score:

students.sort(comparatorGenerator("fName", "lName", "age", "score"));

of course, you don't need to pass in everything, if you want only a primary and secondary you can pass 2 parameters only

students.sort(comparatorGenerator("fName", "lName"));

soniablanche
Автор

Hi, very nice post. I liked the update from "Patrick Ren" in the comments.

This was just about what I was looking for (99%), the missing thing was ordering.
Right now, the code just sorts in ascending order, would be nicer if it could do both ascending and descending.

Well, I did just that and posting the updated code for others who may wish this feature as well.

mode = true, the sort will be ascending. mode = true is the default.
props = can be an array of properties or a single property
arrayOfObjects = ie [
{ id: 1, fName: 'Joe', lName: 'Doe', group: 3 },
{ id: 2, fName: 'Donald', lName: 'Edwards', group: 1 },
{ id: 3, fName: 'James', lName: 'Carls', group: 2 },
{ id: 4, fName: 'Mad', lName: 'Jane', group: 2 } ]

Called like this...

let sorted1 = sortColumns( arrayOfObjects, [ 'fName', 'lName' ] ); // Sorted asc. default
let sorted2 = sortColumns( arrayOfObjects, [ 'fName', 'lName' ], false ); // Sorted desc. must be true

Can also be called like.
The second parameter does not need to be an array if sorting on only one property.

let sorted1 = sortColumns( arrayOfObjects, 'fName' ); // Sorted ascending. default
let sorted2 = sortColumns( arrayOfObjects, 'lName', false ); // Sorted descending. Set to false.

const sortColumns = ( arr, props, mode = false ) => {
if ( ! Array.isArray( props ) ) props = [ props ];

let sorted = arr.sort( ( a, b ) => {
let prop = props[ 0 ];
for ( let idx = 0; idx < props.length; idx++ ) {
const curProp = props[ idx ];
if ( a[ curProp ] !== b[ curProp ] ) {
prop = curProp;
break;
}
}
if ( a[ prop ] === b[ prop ] ) return 0;
return ( a[ prop ] > b[ prop ] ? -1 : 1 ) * ( mode ? -1 : 1 );
} );
return sorted;
};

danhuckson
Автор

Hi

Thankyou for this wonderful tutorial.
this looks really great. Just have another doubt. How can i extend if i have 3rd or 4th items as well to sort??

Thanks in advance

ramthenmala
Автор

Would be great if there are 3 btns on clicking it'll sorts arrays in 3 different ways like sort by value desc or ASC or by date etc

MuhammadAdnan.
Автор

Very interesting, but it can be more interesting if you generalize the propblem: sort by as many props as you wish:
function sortByProps(arr, ...props) {
arr.sort((a, b) => {
// find the first prop that makes a difference
let prop = props[0];
for (let i = 0; i < props.length; i++) {
const curProp = props[i];
if (a[curProp] !== b[curProp]) {
prop = curProp;
break;
}
}
// still needs a eqaul-or-not test since the difference maker prop may not exist
if (a[prop] === b[prop]) return 0;
return a[prop] < b[prop] ? -1 : 1;
})
}

patrickren
Автор

Yea... so 'double sort' isnt a real thing. The sort is either merge, or quick sort.

benjamin