Jay
Jay

Reputation: 37

Jquery, Pass Input Data to an Array

I have a set of array on the text field

<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Jan">

How to can I prevent passing duplicate array

this is my jquery code

  $(document).on("click", ".open_modal", function() {

  //var values = $('input[name^="owner"]').map((i, a) => a.value).get();
  var values = $('input[name="owner[]"]').val();


  if(values == values) {
    alert('exist');  /* how to validate duplicate array */
  }
  $("#owner_value").val(values);

});

Upvotes: 1

Views: 984

Answers (7)

Ahmed Maruf
Ahmed Maruf

Reputation: 511

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);

Upvotes: 0

Akhil Aravind
Akhil Aravind

Reputation: 6130

We can use Array.filter() to filter duplicate values, values.filter((a, b) => values.indexOf(a) === b);

Before that we need to push all the values to an array. This is what I did

var values = [];
    $('input[name="owner[]"]').each(function() {
        values.push($(this).val());
    });

var $ = jQuery;
 $(document).on("click", ".open_modal", function() {
var values = [];
var owners = ['john', 'wons', 'kolins'];
$('input[name="owner[]"]').each(function() {
    values.push($(this).val());
});
values = [...values, ...owners]; // here we merge both arrays and then remove the duplicates. 
  if(values.length) {
  values = values.filter((a, b) => values.indexOf(a) === b);
   // console.log(values); // now duplicates are removed.    
  }
  var htmlContent='';
  values.forEach((user)=>{
    if(user){
    htmlContent +=`<p>${user}</p></br>`;
    }
  })
  
  $("#owner_value").html(htmlContent);

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"></script>
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Reys">
<input type="text" name="owner[]" value="Jan">

<p> Test btn </p>
<button class="open_modal">Open Modal </button>

<div id="owner_value"></div>

Upvotes: 1

User863
User863

Reputation: 20039

Using $.unique()

var values = $.unique($('input[name="owner[]"]').map((i, el) => el.value).get())

console.log(values)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Jan">

Upvotes: 0

rajesh
rajesh

Reputation: 219

Please run below code it will remove duplicate records

  var myArray = ["Hardik", "Rajesh", "Sagar", "Hardik", "Sanju"];

  var myNewArray = myArray.filter(function(elem, index, self) {
      return index === self.indexOf(elem);
  });

Upvotes: 0

Christian Carrillo
Christian Carrillo

Reputation: 2761

using reduce can prevent repeat value:

$(document).ready(() => {
  const $values = $('input[name^="owner"]').map((i, a) => a.value).get()

  const $filterValues = $values.reduce((acc, item) => (!acc.includes(item) && acc.push(item), acc), [])
  console.log($filterValues)
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Jan">

Upvotes: 1

Mohamed Farouk
Mohamed Farouk

Reputation: 1107

You can use mix of map and includes like below:

var existingValues = [];
  var values = $('input[name^="owner"]').map((i, a) => {
    if (!existingValues.includes(a.value)) {
      existingValues.push(a.value);
      console.log(a.value);
      return a;
    }
  });

function getUnique() {
  var existingValues = [];
  var values = $('input[name^="owner"]').map((i, a) => {
    if (!existingValues.includes(a.value)) {
      existingValues.push(a.value);
      console.log(a.value);
      return a;
    }
  });
  console.log(values.length);
  console.log(values);
}

getUnique();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Rey">
<input type="text" name="owner[]" value="Jan">

Upvotes: 0

Daniel Smith
Daniel Smith

Reputation: 1734

Index of all items in an array with the index of the first occurrence of the same item, If indexes are not the same returns it as duplicate.

function getUnique(array){
    var uniqueArray = [];
    for(i=0; i < array.length; i++){
        if(uniqueArray.indexOf(array[i]) === -1) {
            uniqueArray.push(array[i]);
        }
    }
    return uniqueArray;
}

var names = ["John", "Peter", "Clark", "Harry", "John", "Alice"];
var uniqueNames = getUnique(names);
console.log(uniqueNames);

Upvotes: 0

Related Questions