-1

I program a function that give me all values of some input checkboxes and include them into an array.

Function:

$('#area_tbl .checkbox').each(function(){
    /*for(var i = 0; i < test.length; i++){
        if(test[i].PLZ === $(this).find('.area-checkbox').val()){
            alert('Gleich');
        }else{
            alert('nicht gleich');
        }
    }*/
    test.push({PLZ:$(this).find('.area-checkbox').val()});
});

My array looks like this:

[Object { PLZ="42799"}]

That's fine!

Now I include automatically more checkboxes with more values. After that my function is refreshing and I include the 'new' values.

Now my problem is that my array looks like this:

 [Object { PLZ="42799"}, Object { PLZ="42799"}, Object { PLZ="51399"}]

You can see PLZ='42799' is twice.

I want to find the duplicate values and delete them from my array. I try it with the if clause in my function. But nothing works for me.

mplungjan
  • 155,085
  • 27
  • 166
  • 222

3 Answers3

1

Assuming that value of each checkbox is unique, you need to reset the test value before running this each iterator

  test = [];
  $('#area_tbl .checkbox').each(function(){
        test.push({PLZ:$(this).find('.area-checkbox').val()});
   });
gurvinder372
  • 64,240
  • 8
  • 67
  • 88
0

You could use a memory

    // The memory will be a simple list with the already added elements. Firstly empty
    memory = []

    // we loop over ther checboxes
    $('#area_tbl .checkbox').each(function(){

        // we store the value
        var v = $(this).find('.area-checkbox').val();

        // If memory doesn't content the value... (its position is -1)
        if(memory.indexOf(v) == -1){

            // we store the object and we update the memory
            test.push({PLZ:v});
            memory.push(v);
        }

    });
Luis González
  • 2,847
  • 22
  • 42
0

You could use a temporary object and look up with accessing the property:

var object= {};

$('#area_tbl .checkbox').each(function() {
    var v = $(this).find('.area-checkbox').val();
    if (!object[v]) {
        test.push({PLZ: v});
        object[v] = true;
    }
});
Nina Scholz
  • 351,820
  • 24
  • 303
  • 358