shanebo asked on IRC today:
twhat is ze cleanest way to remove duplicate items from an array
I wrote a few solutions until I got what I think is a fairly quick and short snippet to remove duplicate items in an array. It\’s really basic. There are probably a few cases this doesn\’t cover.. such as objects with different ordered items but containing the same contents. I also didn\’t test these solutions for their performance.
Assuming the following code before each solution:
var orig = [\'a\', \'a\', \'b\', \'c\', \'b\'], arr = [];
1. Execute a function during each loop of the original array that checks if the new array contains the item using the Array.contains method. If it doesn\’t exist, then add the item to the new array with the Array.push method.
orig.each(function(item){ if (!arr.contains(item)) {arr.push(item);} });
2. Same as 1. but checks for the index of the item in the new array. If the item doesn\’t exist in the new array, Array.indexOf method will return -1. If so, then add the item to the new array with the Array.push method.
orig.each(function(item){ if (arr.indexOf(item) == -1) {arr.push(item);} });
3. Execute the MooTools Array.include method, which is bound to the new array, during each loop of the original array. The Array.include method will be executed to include the item in the original array if the new array does not already contain the item.
orig.each(arr.include.bind(arr));
4. Same as 3. with the exception that the Array.include method isn\’t bound to the new array prior to executing the loop. The Array.include will be bound to the second argument, in this case the new array, during the loop.
orig.each(arr.include, arr);
// or
orig.filter(arr.include, arr);
// or
orig.map(arr.include, arr);
2 thoughts on “Dedupe an Array with MooTools”