DEV Community

loading...
Cover image for Sorting Unsortables:  Using .sort() in the  wild

Sorting Unsortables: Using .sort() in the wild

akinghill profile image Austin Hill ・2 min read

The Problem

I'm working on a website that lists its employees. The owner of the website wants the employees with a title of 'Developer' to display in front of any other title. The problem is that the data for all the for all the employees is pulled in from a CMS, and that data is ordered according to the date it was input.

My data looks like this:

const data = [
  {
    name: 'John',
    title: 'Developer',
  },
  {
    name: 'Meg',
    title: 'CEO',
  },
  {
    name: 'Ken',
    title: 'Designer',
  },
  {
    name: 'Will',
    title: 'Developer',
  }
];
Enter fullscreen mode Exit fullscreen mode

The Solution

I need to sort the data that comes from the CMS, so that all the employees with a title of 'Developer' appears first. .sort() seems like the right method to user here, but how do we sort according to a title of an object property?

Here is how:

const sortedData = data.sort(employee => {
  if(employee.title === "Developer"){
    return -1
  }else {
    return 1
  }
}
Enter fullscreen mode Exit fullscreen mode

The explanation

So how does this code actually work? First we need to create a variable that can store the sorted data, since .sort() returns a new array, rather than mutating the array it is called on. Next we pass in some 'compare function' into .sort(), I used an anonymous function here. How the compare function works in sort is, when 1 gets returned the current item being looked at gets moved one space to the right, when -1 is returned that item being looked at is moved one space to the left. Once the sorting is done, all of the employees with a title of developer will appear at the beginning of the array! A quick example of sorting 'unsortable' data with .sort().

Would you have solved this another way? Let me know!

Stay in touch with me over on Github

Discussion (0)

pic
Editor guide