0

I am trying to put a condition in jQuery's map function. My issue is that I don't want the same number in the map function value. When it is the same I want to display an alert box. My map function code is like this:

var rankbox= $('input[type=text][class = cate_rank]').map(function() {
  return this.value;
}).get();

If I get a value like 1,2,3,4,5 it's ok, but if I get a value like 1,2,3,2,5, I want to display an alert box. Is it possible?

How to put a condition in jQuery's map function?

function  change_rank() {
  var rankbox= $('input[type=text][class = cate_rank]').map(function() {
    if() {
    } else { }
    return this.value;
  }).get();
dda
  • 6,030
  • 2
  • 25
  • 34
solanki
  • 208
  • 1
  • 4
  • 18

4 Answers4

0
var vals = []
$('input[type=text][class = cate_rank]').each(function(){
    if($(this).val() && (typeof vals[$(this).val()] == 'undefined')){
        vals[$(this).val()] = 1;
        var last_val = $(this).val();
    }else if($(this).val() && (typeof last_val != 'undefined')  && parseInt(last_val) > parseInt($(this).val())){
        alert('Whooah! Something went terribly wrong! Inputs don\'t have values ordered incrementally!');
    }else{
        alert('Whooah! Something went wrong! We got two inputes with same value!');
    }
});
Flash Thunder
  • 11,672
  • 8
  • 47
  • 91
0

Check this,

var rankbox= $(".test").map(function() {
  return this.value;
}).get();

var sorted_arr = rankbox.slice().sort(); 

var results = [];
for (var i = 0; i < rankbox.length - 1; i++) {
    if (sorted_arr[i + 1] == sorted_arr[i]) {
        results.push(sorted_arr[i]);
    }
}
var rankbox= $(".test").map(function() {
  if($.inArray(this.value, results) > -1){
  alert(this.value+" is duplicate");
  }
  return this.value;
}).get();

I took reference of this link

Community
  • 1
  • 1
Rahul
  • 18,271
  • 7
  • 41
  • 60
0

If you are Looking to check dup you can try this:

var x=[1,2,3,2,5]
var has=!x.every(function(v,i) {
   return x.indexOf(v) == i;
 });

 console.log(has);//true means dup found else not found.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Suchit kumar
  • 11,809
  • 3
  • 22
  • 44
0

you can try with a object. check this:


function  change_rank() {
  var temp = {};
  var rankbox= $('input[type=text][class = cate_rank]').map(function() {
    if(temp[this.value]==undefined) {
      temp[this.value] = this.value;
    } else {
      alert('the same value');
    }
    return this.value;
}).get();
Cin Stev
  • 36
  • 2