arch1ve
arch1ve

Reputation: 183

console.log(array) returns empty, but console.log(array.length) doesn't return 0

I have the following javascript

var filtered = [];

$('#footballCheck').on('change', function() {
  if ($('#footballCheck').is(':checked')) {
    for (var i = 0; i < fa_names.length; i++) {
      if (fa_names[i]["facility_activity"].toLowerCase().indexOf("football") >= 0) {
        filtered.push(fa_names[i]);
      }
    }

    filtered.sort(SortByName);
    $('#mCSB_1_container').empty(".facility-name");
    for (var k = 0; k < filtered.length; k++) {
      $('#mCSB_1_container').append('<div class="row facility-name">\
                                             <button class="btn btn-default btn-fill btn-menu" date-name="' + filtered[k]["facility_name"] + '">' + filtered[k]["facility_name"] + '</button></div>');
      $('#facilities-body').mCustomScrollbar("update");
    }
  } else {
    for (var j = 0; j < filtered.length; j++) {
      if (filtered[j]["facility_activity"].toLowerCase().indexOf("football") >= 0) {
        delete filtered[j];
      }
    }
    console.log(filtered);
    console.log(filtered.length);
    if (filtered.length > 0) {
      filtered.sort(SortByName);
      $('#mCSB_1_container').empty(".facility-name");
      for (var k = 0; k < filtered.length; k++) {
        $('#mCSB_1_container').append('<div class="row facility-name">\
                                                 <button class="btn btn-default btn-fill btn-menu" date-name="' + filtered[k]["facility_name"] + '">' + filtered[k]["facility_name"] + '</button></div>');
        $('#facilities-body').mCustomScrollbar("update");
      }
    } else {
      $('#mCSB_1_container').empty(".facility-name");
      for (k = 0; k < fa_names.length; k++) {
        $('#mCSB_1_container').append('<div class="row facility-name">\
                                                 <button class="btn btn-default btn-fill btn-menu" date-name="' + fa_names[k]["facility_name"] + '">' + fa_names[k]["facility_name"] + '</button></div>');
        $('#facilities-body').mCustomScrollbar("update");
      }
    }
  }
});

that should do the following:

Here is the fiddle.

Background: The checkboxes act as filters for a search and the filtered array stores those filtered values (in no other place other than what is in that fiddle the filtered array is changed yet).

My problem is that console.log(filtered) returns [] and console.log(filtered.length) does NOT return 0 and it should. Why does this happen and how can I fix it?

Upvotes: 0

Views: 453

Answers (1)

Tushar
Tushar

Reputation: 87203

delete on array doesn't change the length of array. It just sets the element value to undefined. Use splice to remove element from array.

Upvotes: 1

Related Questions