Home > Software design >  How can I can split one array into two arrays with condition on element
How can I can split one array into two arrays with condition on element

Time:08-24

I'm trying to display a graph with plotly.js. For this, I have an array called data, which contains all my data. But I want to display only selected elements/datas by the user. So, I want to have two arrays with displayed elements and deleted elements.
My project works with vuejs and plotly.js

Here is my code :

//clusterCheckboxes are my checkboxes, they are all selected by default
const clusterCheckboxes = document.querySelectorAll("input[type='checkbox'].cluster")
      //My newData contains the displayed datas
      this.newData = []
      //deletedLines containes not displayed data
      this.deletedLines = []

      
      for (let i = 0; i < clusterCheckboxes.length; i  ) {
        for(let j = 0; j < toRaw(this.data).length; j  ){
          //Si le checkbox est cochée on ajoute les lignes correspondantes à newData
          if(clusterCheckboxes[i].checked){
            this.newData.push(toRaw(this.data)[j])
          }else{
            this.deletedLines.push(toRaw(this.data)[j])
          }
        }
      }
      //This lines create a new plotly graph
      Plotly.newPlot('myDiv', this.newData);```

CodePudding user response:

I am assuming clusterCheckboxes and data share the same length, then you can use the same index and split them based on the condition.

//clusterCheckboxes are my checkboxes, they are all selected by default
const clusterCheckboxes = 
document.querySelectorAll("input[type='checkbox'].cluster")
  //My newData contains the displayed datas
  this.newData = []
  //deletedLines containes not displayed data
  this.deletedLines = []

  
    for(let j = 0; j < toRaw(this.data).length; j  ){
      //Si le checkbox est cochée on ajoute les lignes correspondantes à 
newData
      if(clusterCheckboxes[j].checked){
        this.newData.push(toRaw(this.data)[j])
      }else{
        this.deletedLines.push(toRaw(this.data)[j])
      }
    }
  //This lines create a new plotly graph
  Plotly.newPlot('myDiv', this.newData);

CodePudding user response:

Assuming your checkboxes and data are the same length, you can just use filter to separate the data:

const clusterCheckboxes = document.querySelectorAll("input[type='checkbox'].cluster")

const rawData = toRaw(this.data)

this.newData = rawData.filter((_, i) => clusterCheckboxes[i].checked)

Plotly.newPlot('myDiv', this.newData)

If you really want the deletedLines value you can generate it the same way:

this.deletedLines = rawData.filter((_, i) => !clusterCheckboxes[i].checked)
  • Related