Skip to content

Commit ef5fa17

Browse files
Create sorting_an_array_of_objects.js
A Javascript algorithm
1 parent cd7fec3 commit ef5fa17

File tree

1 file changed

+53
-0
lines changed

1 file changed

+53
-0
lines changed

Diff for: sorting_an_array_of_objects.js

+53
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
/* Suppose we have an araay of Objects with various properties.
2+
We want to sort the array of those similar objects based on a particular property
3+
or also a combonation of two or more properties.
4+
We will achieve this using the Compare function*/
5+
6+
7+
// An array of a few Soccer Players
8+
9+
const players = [
10+
{ name: 'Cristiano Ronaldo', team: 'Juventus', age:35 },
11+
{ name: 'Lionel Messi', team: 'Barcelona', age:32 },
12+
{ name: 'Eden Hazard', team: 'Real Madrid', age: 29 },
13+
{ name: 'Neymar Jr', team: 'Paris Saint-German', age:28 },
14+
];
15+
//Note that these statistics can change, these are correct as per 3 May,2020
16+
17+
/*We can use the following compare function to sort this array of players according to their teams*/
18+
19+
function compare(a, b) {
20+
// Use toUpperCase() to ignore character casing
21+
const teamA = a.team.toUpperCase();
22+
const teamB = b.team.toUpperCase();
23+
24+
let comparison = 0;
25+
if (teamA > teamB) {
26+
comparison = 1;
27+
}
28+
else if (teamA < teamB) {
29+
comparison = -1;
30+
}
31+
//If teamA===teamB, no change occurs
32+
33+
return comparison;
34+
}
35+
//NOTE: A positive value of the return value means teamA comes after teamB and vice-versa
36+
37+
//Function Call
38+
39+
players.sort(compare);
40+
41+
/*returns:-
42+
(4) [{…}, {…}, {…}, {…}]
43+
0: {name: "Lionel Messi", team: "Barcelona", age: 32}
44+
1: {name: "Cristiano Ronaldo", team: "Juventus", age: 35}
45+
2: {name: "Neymar Jr", team: "Paris Saint-German", age: 28}
46+
3: {name: "Eden Hazard", team: "Real Madrid", age: 29}
47+
length: 4
48+
__proto__: Array(0)
49+
*/
50+
51+
//Similarly 'compare' function can also be used to sort the players according to their age : Try to figure out yourself :p
52+
53+

0 commit comments

Comments
 (0)