Skip to content

Instantly share code, notes, and snippets.

@thomasjao
Created June 15, 2015 16:41
Show Gist options
  • Save thomasjao/d7d4fb159c1a3227fde2 to your computer and use it in GitHub Desktop.
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
/* 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