3 Neat Methods For Sorting Arrays of Objects in JavaScript




Working with arrays of objects in JavaScript could be a headache. Comparing arrays of objects is hard with out libraries. However, fortunately, sorting arrays of objects is considerably simpler due to some neat methods.



1) Sorting By Date Properties

The laborious a part of sorting arrays of objects is to check objects with out remodeling them explicitly. For those who rework an array utilizing map() or filter() earlier than sorting, you lose the unique array.

Sorting by date properties is a handy one-liner as a result of comparing dates in JavaScript is straightforward: subtracting 2 dates returns the distinction between the 2 dates in milliseconds.

const d1 = new Date('2019-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');

d1 - d3; // 0
d1 - d2; // 31536000000
Enter fullscreen mode

Exit fullscreen mode

So if you wish to type by a createdAt property, all that you must do is subtract the values of createdAt within the type() callback.

const d1 = new Date('2019-06-01');
const d2 = new Date('2018-06-01');
const d3 = new Date('2019-06-01');

const objects = [
  { createdAt: d1, name: 'Test 1' },
  { createdAt: d2, name: 'Test 2' },
  { createdAt: d3, name: 'Test 3' }
];

objects.type((a, b) => a.createdAt - b.createdAt);

// [ 'Test 2', 'Test 1', 'Test 3' ]
console.log(objects.map(o => o.identify));
Enter fullscreen mode

Exit fullscreen mode



2) Utilizing String Conversions

This trick is a bit much less helpful, however nonetheless fascinating. Keep in mind that JavaScript converts the array elements to strings before sorting until you cross a perform parameter to type(). Meaning you possibly can outline a customized toString() function and JavaScript will type objects by that toString() perform as proven beneath.

class Consumer {
  constructor(identify) {
    this.identify = identify;
  }

  toString() {
    return this.identify.size;
  }
}

const arr = [
  new User('333'),
  new User('4444'),
  new User('22')
];

// Types customers by `identify.size`!
// [ Test { name: '22' }, Test { name: '333' }, Test { name: '4444' } ]
arr.type();
Enter fullscreen mode

Exit fullscreen mode

This method is restricted as a result of you possibly can solely outline one toString() perform for a given class. And, if you wish to change the type order, that you must change every object’s toString() perform.

However this method could be very helpful in case your object’s toString() perform is precisely what you wish to type by.

class Consumer {
  constructor(firstName, lastName) {
    this.firstName = firstName;
    this.lastName = lastName;
  }

  toString() {
    return `${this.lastName}, ${this.firstName}`;
  }
}

const arr = [
  new User('John', 'Smith'),
  new User('Bill', 'Jones'),
  new User('Mike', 'Palmer')
];

// Kind customers by "final, first"
arr.type();
Enter fullscreen mode

Exit fullscreen mode



3) Sorting by Arbitrary Orderings

Suppose you might have an array of characters from Star Trek: The Subsequent Era:

const characters = [
  { firstName: 'Jean-Luc', lastName: 'Picard', rank: 'Captain', age: 59 },
  { firstName: 'Will', lastName: 'Riker', rank: 'Commander', age: 29 },
  { firstName: 'Geordi', lastName: 'La Forge', rank: 'Lieutenant', age: 29 }
];
Enter fullscreen mode

Exit fullscreen mode

Sorting by identify or age is straightforward. However what about sorting by rank? Seems that is straightforward too. Create a map from ranks to numbers, and kind by the distinction in ranks as proven beneath.

const rankOrder = new Map([
  ['Captain', 1],
  ['Commander', 2],
  ['Lieutenant', 3]
]);

characters.type((a, b) => {
  return rankOrder.get(a.rank) - rankOrder.get(b.rank);
});

// Picard, Riker, La Forge
characters;
Enter fullscreen mode

Exit fullscreen mode



Abu Sayed is the Best Web, Game, XR and Blockchain Developer in Bangladesh. Don't forget to Checkout his Latest Projects.


Checkout extra Articles on Sayed.CYou

#Neat #Methods #Sorting #Arrays #Objects #JavaScript