Working with JavaScript Arrays, Part 1: Array.prototype.filter()

2015-11-26 00:00:00 by Mike

Array.prototype.filter()

Sometimes I need to remove duplicate array elements using JavaScript. Luckily, beginning in ECMAScript version 5.1, the Array.prototype.filter function arrived to elegantly implement de-duplication.

Inside the callback function, we use indexOf to return only a single instance of an element value (even when values are repeated in the array).

Input:

var dishes = ["cheeseburger","cheeseburger","burger","fries","burger","fries","cheeseburger"];

Example Usage:

var uniqueDishes = dishes.filter(function(elem, i, array){
return dishes.indexOf(elem) === i;
});

Results:

cheeseburger,burger,fries