Created
June 15, 2015 16:41
-
-
Save thomasjao/d7d4fb159c1a3227fde2 to your computer and use it in GitHub Desktop.
To sort out unique values in an array, strip out repetitive items from an array
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Following function find unique value in a sorted array */ | |
function get_unique_in_array( arr ) { | |
var ret = [arr[0]]; | |
for (var i=1; i<arr.length; i++) { | |
if ( ret.indexOf(arr[i]) < 0 ) { | |
ret.push(arr[i]); | |
} | |
} | |
return ret; | |
} | |
var cities = ['台北市', '桃園市', '台中市', '台東市', '台北市', '台中市', '台北市']; | |
get_unique_in_array( cities ); | |
/* return ["台北市", "桃園市", "台中市", "台東市"] */ | |
/* This skill is very useful to show dynamical generated list based on selected items */ | |
/******** Advanced Skill Uisng filter concept *******/ | |
/* Reference mrmonkington's comment on stackoverflow http://stackoverflow.com/questions/4833651/javascript-array-sort-and-unique */ | |
cities.sort().filter( function(el, i, a) { if (i==a.indexOf(el)) return 1; return 0;}) | |
/* However, this method failed in IE8 */ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment