Arrays with unique entries
From MapbenderWiki
The goal is to delete multiple occurences of an item in an array.
Example:
[0] => 1 [1] => 2 [2] => 1 [3] => 3
shall be changed into
[0] => 1 [1] => 2 [2] => 3
Contents |
PHP
array_unique
see php.net. This function preserves the keys, the above would be changed into
[0] => 1 [1] => 2 [3] => 3
which is disastrous if you use for and not foreach
array_keys, array_flip
the following does not preserve the keys
array_keys( array_flip( someArray ));
so the result would indeed be
[0] => 1 [1] => 2 [2] => 3
JavaScript
No solution yet.
There is a native jQuery function that does exactly this, but it only works if the array elements are DOM elements.
two quick functions that seem to do the trick
Maybe these functions provide what you need (further testing needed).
function arrayUnique(arr) {
var unq_arr = [];
for(var i=0, len = arr.length; i<len; i++) {
if (typeof arr[i] !== 'undefined' && indexOf(arr[i], unq_arr) === -1) {
unq_arr.push(arr[i]);
}
}
return unq_arr;
}
function indexOf(needle, haystack) {
for(var i=0,len=haystack.length; i<len; i++) {
if (typeof haystack[i] !== 'undefined' && haystack[i] == needle) {
return i;
}
}
return -1;
}
var arr = [1,2,1,3]; console.dir( arr ) console.dir( arrayUnique(arr) );
