javascript - Check for duplicates in an array -
i have function check serialized form data if there duplicates values in it.
s = $('#multiselectform').serialize(); var x = []; var y = []; x = s.split("&"); (var = x.length - 1; >= 0; i--) { y.push(x[i].split("=")); }; var c = 0; var e = 0; (var = y.length - 1; >= 0; i--) { if (y[i][1] == y[c][1]) { e++; $('.duplicatealert').show(); } else { $('.duplicatealert').hide(); }; c++; };
basically, split string produced serialize()
function , push data arrays.
the array i'm trying parse looks this:
array [ array [ 0: 'my_field1', 1: 'val1' ], array [ 0: 'my_field2' 1: 'val2' ], array [ 0: 'my_field3' 1: 'val1' ] ]
are there better ways same task? maybe shorter?
- create empty array hold matches
- loop through array. on each iteration...
- loop through matches array , check if item same value exists. if does, set matched flag.
- check if matched flag has been set
- if so, alert user
- if not add item matches.
var array = [ [ 'my_field1', 'val1' ], [ 'my_field2', 'val2' ], [ 'my_field3', 'val1' ], [ 'my_field4', 'val2' ], [ 'my_field5', 'val3' ] ], matches = [], match = false; for(var = 0, j = array.length; < j; i++) { match = false; for(var k = 0, l = matches.length; k < l; k++) { if(matches[k][1] == array[i][1]) { match = true; } } if(match) alert('duplicate!'); else matches.push(array[i]); }
Comments
Post a Comment