Cannot read property ‘slice’ of undefined in jQuery


Ask A Question





Login To post a question

I am using slice() function inside $.each() array. It shows this error when the first half of the array values have the same string. $name is coming from a button which always has a different value i.e question1, question2.

I tried when the array is like var arr = ["question1Answer1", "question2Answer2"]; then function works OK but when I push more values starting with question2 and want to remove these values than above error shows in the console.

    var arr = ["question1Answer1", "question2Answer2", "question2Answer3"];
    refreshArrange = function($name) {

      $.each(arr, function(index, value) {
        var newStr = '';
        var newStr2 = '';

        newStr = value.slice(0, 9);
        newStr2 = value.slice(0, 10);

        if(newStr == $name) {
          var ind = arr.indexOf(value);
          if (ind > -1) {
            arr.splice(ind, 1);
            console.log('working Ok');
          }

        }else {

        }

      });

      console.log(arr);
    }

I want to remove the 2nd and 3rd value of array because the coming value of $name is question2. I am splitting up the array values and compare the first half with $name and removing it. But this error occurs.
I don’t know where the problem is.

I am sorry if this is a stupid question. I know I didn’t explain the problem properly.

For more info please click herehttps://stackoverflow.com/q/57586580



Have a question or need a custom quote?
info@smartinfocare.com