There are many ways to implement the solution: I have included few of them
HTML:
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Jan">
Naive solution:
(function($){
$(document).on("click", ".submit", function() {
var values = $('input[name="owner[]"]');
var stores = [];
values.each(function(index, value){
stores.push($(this).val());
});
for(var i = 0; i <= stores.length; i++) {
for(var j = i; j <= stores.length; j++) {
if(i != j && stores[i] == stores[j]) {
console.log('Duplicates exists!');
}
}
}
});
})(jQuery);
The above code implements two nested loops to find duplicates!
Naive approach with slightly better performance:
(function($){
$(document).on("click", ".submit", function() {
var values = $('input[name="owner[]"]');
var stores = [];
values.each(function(index, value){
stores.push($(this).val());
});
var counts = [];
for(var i = 0; i <= stores.length; i++) {
if(counts[stores[i]] === undefined) {
counts[stores[i]] = 1;
} else {
console.log('Duplicate exsist!');
}
}
});
})(jQuery);
behind the process this approach is followed in most of the standard libraries or existing functions with some additional performance improvements.
Here is another way of doing the same using some existing helper functions:
(function($){
$(document).on("click", ".submit", function() {
var values = $('input[name="owner[]"]');
var stores = [];
values.each(function(index, value) {
console.log($(this).val());
if ($.inArray($(this).val(), stores) == -1){
console.log('No Duplicate');
stores.push($(this).val());
}else{
console.log('Duplicate Exist');
}
});
});
})(jQuery);