1

I have function where I push items to array by scrolling the page but the problem is that pushed items are repeating instead of pushing new items.

Code

onScroll(): void {
      console.log('scrolled');
      var i,j,newArray,chunk = 10;
      for (i=0,j=this.listOfData.length; i<j; i+=chunk) {
          newArray = this.listOfData.slice(i,i+chunk);
          this.results = this.results.concat(newArray);
      }
}

My this.listOfData array has 19 items and it only gets 19 to 10 (repeating) 9 to 1 never shows.

Source of this code

Any idea?

Update

In case you have hard time understand my point i recorder small video of my issue Watch

mafortis
  • 6,750
  • 23
  • 130
  • 288

2 Answers2

1

Your code is failing because of the issue mentioned by Aditya in the answer above. Change your code like this :

       onScroll(): void {
          console.log('scrolled');
          var index,newArray,chunk = 10;
          if(this.result.length == 0){
              newArray = this.listOfData.slice(0,chunk);
              this.results = this.results.concat(newArray);
          }
          else if(this.results.length < this.listOfData.length){
             index=this.result.length-1;
             newArray = this.listOfData.slice(index,index+chunk);
             this.results = this.results.concat(newArray);
          }
       }
Naveen Chahar
  • 561
  • 3
  • 10
0

Since every time your function executes your i value will be set to 0 and chunk is 10, it will always slice out the same chunk from your array. This is why you have repeating data.

Array.prototype.slice does not modify the original array, if that is where the confusion is arising.

In such a case alter your code to:

onScroll(): void {
      console.log('scrolled');
      var i,j,newArray,chunk = 10;
      for (i=0,j=this.listOfData.length; i<j; i+=chunk) {
          newArray = this.listOfData.splice(i,i+chunk);
          this.results = this.results.concat(newArray);
      }
}

Array.prototype.splice will delete the chunk from the original array and return the deleted chunk.

Aditya Menon
  • 744
  • 5
  • 13
  • What exactly are you trying to achieve? I recommended splice since it seemed like that was what you were trying to do. If you can explain your problem better, I may be able to give a better solution – Aditya Menon Nov 25 '20 at 05:32
  • Ok, `issue` remember that I said my `19 to 10 (repeating)`? now they are not repeating nor `9 to 1` is printing! it just stops on first load. `what I want` at first load show `19 to 10` and when I scroll down add `9 to 1` into `19 to 10` so I will have full list `19 to 1` – mafortis Nov 25 '20 at 05:37
  • What if your data had (let's say) 35 items. Do you want to show all 35 items on scrolling down once or just the next 10 ? @mafortis – Naveen Chahar Nov 25 '20 at 06:22
  • then it should show like: `10-10-10-5` it just adds up – mafortis Nov 25 '20 at 06:26