DEV Community

Jay Setlock
Jay Setlock

Posted on • Updated on

Using Filter and Sort in JavaScript

Getting a grasp of filtering and sorting arrays in JavaScript can be quite confusing at first. Let's look at example of an array of objects that a substitute teacher might collect and see if we can't make it make sense.

const students = [
  { id:105, name: "Jessica",   is_present:true },
  { id:101, name: "Denise",    is_present:true },
  { id:103, name: "Blake",     is_present:false},
  { id:102, name: "Jaqueline", is_present:true },
  { id:104, name: "Aaron",     is_present:true },
]
Enter fullscreen mode Exit fullscreen mode

Let's say we wanted to see who was not present in class. We would use .filter like so:

let filteredStudents =
students.filter(student=>student.is_present===false)
Enter fullscreen mode Exit fullscreen mode

The result would be:

filteredStudents=[{id: 103, name: 'Blake', is_present: false}]
Enter fullscreen mode Exit fullscreen mode

What if you wanted more than just a subset of your original array out of your filter operation? Since the filter is really answering a question then the result could be used to create new data.

We could guess what the result of the following would be:

let filteredStudents =  
students.filter(student=>student.name.includes("J"))
Enter fullscreen mode Exit fullscreen mode
 filteredStudents = [
  { id:105, name: "Jessica",   is_present:true },
  { id:102, name: "Jaqueline", is_present:true }
]
Enter fullscreen mode Exit fullscreen mode

But what if we wanted a new array that specified that the names in the array had passed the filter test?

let filteredStudentsJ =
students.filter(student=>student.name.includes("J"))
.sort((a,b)=>a.name>b.name?1:-1)
.map(filteredStudent=>({
   name:filteredStudent.name,
   id:filteredStudent.id,
   includes_J:true}))
Enter fullscreen mode Exit fullscreen mode

We get a new array of objects that has the 'includes_J' key instead of 'is_present'.

filteredStudentsJ =[
 {name: 'Jaqueline', id: 102, includes_J: true}
 {name: 'Jessica', id: 105, includes_J: true}
]
Enter fullscreen mode Exit fullscreen mode

The filteredStudentsJ array is also now in alphabetical order due to this tiny yet powerful piece of code:

array.sort((a,b)=>a.name>b.name?1:-1)

Enter fullscreen mode Exit fullscreen mode

Huh? .sort is being asked to compare (in this case) the name key of a pair of objects within the array. We want ascending order in this case so we are using greater than (>) for our comparison. This comparison is used in a ternary statement that is applied to the index. If the value of a is greater than b, you add one to its index, if not you subtract 1 from its index. .sort then repeats the process through the array until no more sorting can be done.

Phew, now we're ready to take roll.

A substitute teacher takes roll

Top comments (0)