Home > Enterprise >  remove from array by index using values from another array
remove from array by index using values from another array

Time:07-25

I have a large array of data lets call it this.dataSet, I also have an array that looks like this,

this.visibleRows = [1, 6, 52, 92, 96, 98, 100];

This is an array of indexes, and using those indexes I will retrieve data from this.dataSet.

I also want to keep a record of indexes that I don't want to show in another variable this.hiddenRows

Using this.visibleRows and this.dataSet is it possible to get the indexes that not in this.visibleRows?

I thought something like,

this.dataSet.filter((data, index) => {
    if(this.visibleRows.indexOf(index) < 0) {
         this.hiddenRows.push(index);
    }
});

However the above seems to think all rows need removing?

CodePudding user response:

This seems to work fine. I don't think that you actually need hiddenRows

class DataHandler {
 
     dataset = [
     {name: 'first'},
     {name: 'second'}
    ]
    
     visibleRows = [1]
   
   hiddenRows = []
    
    getData(){
      return this.dataset.filter((d, i) => this.visibleRows.includes(i))
    }
    
    getHiddenRows(){
      return Object.keys(this.dataset).filter(i => !this.visibleRows.includes(Number(i)))
    }
   }
   
   const data = new DataHandler()
   
   console.log(data.getData())
   console.log(data.getHiddenRows())

If your dataset is big you can also use this approach

class DataHandler {
 
     dataset = [
     {name: 'first'},
     {name: 'second'}
    ]
    
     visibleRows = [1]
   
    
    getData(){
      return this.visibleRows.map((i) => this.dataset[i] || null).filter(d => d)
    }
     getHiddenRows(){
      return Object.keys(this.dataset).filter(i => !this.visibleRows.includes(Number(i)))
    }
   }
   
   const data = new DataHandler()
   
   console.log(data.getData())
   console.log(data.getHiddenRows())

CodePudding user response:

may be this way perform faster. check it out make a copy of Ur data set

var hiddenData = dataSet.slice();

then remove visible indexes from large indexes to small one in this case U need sort visible indexes array

this.visibleRows = this.visibleRows.sort().reverse();
this.visibleRows.forEach(row=>{
    hiddenData.splice(row,1)
})
  • Related