Filter and Sort in javaScript

Posted in software by Christopher R. Wirz on Fri Aug 03 2012

With the introduction of IE9 over a year ago (March 2011 to be exact), javascript now supports both filter and sort. These operations can be performed on arrays to quickly manipulate a collection.

Note: Filter and sort can only be applied to arrays, not objects. Sort is mutating, filter is not.

Filter removes values. In its predicate function (which is passed into the argument of filter) you specify which values to keep. Filter returns a filtered array, but does not modify the original array.

Sort will order values where a more negative result indicates the first comes before last and a more positive result indicates first comes after last. To this regard, false = 0 and true = 1 such that a boolean could also be returned by the predicate.

Sort returns and modifies the array.

A basic implementation is as follows:

var ages = [32, 18, 12, 21, 42, 28];

function filterAges(agesToFilter, minAge) {

	// check that minAge was passed
	if (typeof(minAge)!='number'){
		minAge = 21;
    return agesToFilter
			// keep values 
			return a >= minAge;
		.sort(function(obj, other){
			// order ascending
			// could also be written obj > other
			return (obj - other); 

			// (other - obj) would be descending

var newAges = filterAges(ages, 21);
// or newAges = filterAges(ages);

// [21, 28, 32, 42]

In this example, filter is performed before sort. This is the standard since filter has no knowledge of order. Also, the smaller the number of elements, the faster the sort will be performed.

Looking for a job?