[英]How can I can split one array into two arrays with condition on element
I'm trying to display a graph with plotly.js.我正在尝试使用 plotly.js 显示图表。 For this, I have an array called data, which contains all my data.
为此,我有一个名为 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.
所以,我想要两个 arrays 显示元素和删除元素。
My project works with vuejs and plotly.js我的项目使用 vuejs 和 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);```
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
和data
共享相同的长度,那么您可以使用相同的索引并根据条件拆分它们。
//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);
Assuming your checkboxes and data are the same length, you can just use filter
to separate the data:假设您的复选框和数据的长度相同,您可以使用
filter
来分隔数据:
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:如果你真的想要
deletedLines
值,你可以用同样的方式生成它:
this.deletedLines = rawData.filter((_, i) => !clusterCheckboxes[i].checked)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.