1

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

});

7 Answers 7

1

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>

Sign up to request clarification or add additional context in comments.

4 Comments

this works. how can i use .join('<br>') because I am trying to join the 2 array into a p tag to my modal $("#owner_html").val(values); this is my <p id="owner_html"></p>
So you are trying to join array 1 and array 2, like [jon, won, don] and [ roy, joy, coy], then display those in a p tag, eg. <p> jon </p> <p> won </p> ..., like., right ?
yes done thank you. can i ask <p>${user}</p></br> what is this (`) why cant i use a (")
Its template literal, you can refer the doc and you will get good info from there rather than me explaining. :). I am bad in explaining bro, sorry. Please check the link developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
1

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">

Comments

0

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

Comments

0

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">

Comments

0

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

Comments

0

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">

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.