0

I'm iterating an array and based on a condition I want to delete the specific element from that array based on index(currently I use). Following is my code which is working perfectly as expected.

var todayWeekNo = new Date().getWeek();
$.each(arr, function (i, j) {
    var isEqual = todayWeekNo == new Date(j.Date).getWeek();
    if (isEqual) {
        delete arr[i];
    }
});

You can see this working fiddle

While looking for a better approach, I came to know that

Delete won't remove the element from the array it will only set the element as undefined.

So I replaced delete arr[i]; with arr.splice(i, 1);

For first 2 iteration it was working fine, whereas it get stuck at the last iteration.

Below is console message(jsfiddle):

index0 arr: [object Object] (index):43
index1 arr: [object Object] (index):43
index2 arr: undefined (index):43
Uncaught TypeError: Cannot read property 'Date' of undefined

Please shed some light on this issue.

Community
  • 1
  • 1
Praveen
  • 55,303
  • 33
  • 133
  • 164

4 Answers4

0

If you are removing an element from the array, you need to make sure the index still matches:

var arr = [0,1,2,3];
var index = 1;

arr[index] // 1
arr.splice(index,1);
index++;
arr[index] // 3 (2 was skipped, because arr[1] === 2 after splice)

Solution:

for (var i=0; i<arr.length; i++) {
  if (cond) {
    arr.splice(i,1);
    i--;
  }
}
Tibos
  • 27,507
  • 4
  • 50
  • 64
0

It looks like $.each() is not handling the modification of array

var todayWeekNo = new Date().getWeek();
for (var i = 0; i < arr.length;) {
    console.log("index" + i + " arr: " + arr[i]);

    var isEqual = todayWeekNo == new Date(arr[i].Date).getWeek();
    if (isEqual) {
        arr.splice(i, 1);
    } else {
        i++;
    }
}

Demo: Fiddle

Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
0

You are using loop to remove elements from array.

Here, while you reach to i=2, array has only one element left. So, it returns undefined.

codingrose
  • 15,563
  • 11
  • 39
  • 58
0

$.each is obvously not handling the modification of the array, i am not sure for (i < arr.length) does either, id rather try:

for (i in arr) {
    console.log("index" + i + " arr: " + arr[i]);

    var isEqual = todayWeekNo == new Date(arr[i].Date).getWeek();
    if (isEqual) {
        arr.splice(i, 1);
    }
}
Alex
  • 9,911
  • 5
  • 33
  • 52