Search code examples
javascriptreactjsloopsfor-loopsplice

Splicing items from an array in a for loop, get typeerror


For an application I am making I want to remove items from an array using checkboxes. This is the function I use:

    for(let article = articleList.length -1; article >= 0; article--)
  
  {
    console.log(article, articleList[article].props.title);
    if(this.whatToShow.article == false){
      if (articleList[article].props.category == "Artikel"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.news == false){
      if (articleList[article].props.category == "Nieuws"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.blog == false){
      if (articleList[article].props.category == "Blog"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.client == false){
      if (articleList[article].props.category == "Client"){
        articleList.splice(article, 1);
      }
    }
    if(this.whatToShow.stories == false){
      if (articleList[article].props.category == "Ervaringsverhaal"){
        articleList.splice(article, 1);
      }
    }
  }

I first had the problem that it wouldn't remove all the items, so I made the loop backwards. Now when I have almost all checkboxes off (all values false) I get a typeerror, but I have no idea what's going wrong here. Can anyone help me?

Thank you in advance :)


Solution

  • It happens because inside the loop you change the array that you iteration over.

    Try to wrap all conditions to if-else like this:

      const articleList = [
        { props: { title: 'first', category: 'Artikel' } },
        { props: { title: 'sec', category: 'Blog' } },
        { props: { title: 'third', category: 'Client' } },
        { props: { title: 'fouth', category: 'Nieuws' } },
      ]
    
      for (let article = articleList.length - 1; article >= 0; article--) {
        console.log(article, articleList[article].props)
        if (this.whatToShow.article == fals && articleList[article].props.category == 'Artikel') {
          articleList.splice(article, 1)
        } else if (this.whatToShow.news == false && articleList[article].props.category == 'Nieuws') {
          articleList.splice(article, 1)
        } else if (this.whatToShow.blog == false && articleList[article].props.category == 'Blog') {
          articleList.splice(article, 1)
        } else if (this.whatToShow.client == false && articleList[article].props.category == 'Client') {
          articleList.splice(article, 1)
        }
      }
    
    

    Or also you can use "continue" instead if-else construction