function removeDuplicates(arr) { arr.sort(); var i = arr.length - 1; while (i > 0) { if (arr[i] === arr[i - 1]) arr.splice(i, 1); i--; } }
A collection of handy code snippets in the languages that I use on a daily basis.
March 23, 2012
Javascript: Remove duplicate values from an array
I did a Google search for different methods of removing duplicate values from an array, and I found a bunch of crappy algorithms that all returned a new array, rather than paring down the original array. So I wrote this, which wouldn't work on identical complex objects, but works great for primitive data types and objects stored by reference.
Labels:
array,
function,
javascript,
js
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment