Is there a way to divide a single array into two separate arrays based on a specific element?

My goal is to create an interactive graph using plotly.js. I have an array named data that contains all the information needed for the graph. However, I want users to be able to select specific elements to display on the graph. To achieve this functionality, I need to maintain two separate arrays: one for displayed elements and one for deleted elements.
The project utilizes vuejs and plotly.js.

Below is a snippet of my code :

//clusterCheckboxes represent checkboxes that are initially selected
const clusterCheckboxes = document.querySelectorAll("input[type='checkbox'].cluster")
//The newData array stores the displayed data
this.newData = []
//The deletedLines array stores the data that is not displayed
this.deletedLines = []

for (let i = 0; i < clusterCheckboxes.length; i++) {
    for(let j = 0; j < toRaw(this.data).length; j++){
        //If the checkbox is checked, add the corresponding lines to newData
        if(clusterCheckboxes[i].checked){
            this.newData.push(toRaw(this.data)[j])
        }else{
            this.deletedLines.push(toRaw(this.data)[j])
        }
    }
}
//Create a new plotly graph with the newData array
Plotly.newPlot('myDiv', this.newData);

Answer ā„–1

If we assume that the arrays clusterCheckboxes and data have the same length, then we can iterate through them using the same index and split them based on a given condition.

//clusterCheckboxes represent checkboxes, all selected by default
const clusterCheckboxes = document.querySelectorAll("input[type='checkbox'].cluster");
//newData will contain displayed data
this.newData = [];
//deletedLines will contain data not displayed
this.deletedLines = [];

for(let j = 0; j < toRaw(this.data).length; j++){
    //If checkbox is checked, add corresponding lines to newData
    if(clusterCheckboxes[j].checked){
        this.newData.push(toRaw(this.data)[j]);
    } else {
        this.deletedLines.push(toRaw(this.data)[j]);
    }
}
//This section creates a new plotly graph
Plotly.newPlot('myDiv', this.newData);

Answer ā„–2

To ensure that your checkboxes and data match up in length, a simple solution is to utilize the filter function to separate the data:

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

const rawData = convertData(this.data)

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

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

If you also require the deletedLines value, you can achieve this using a similar approach:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Regular expressions for intricate uppercase-lowercase situations

Looking for assistance with an app that converts text to braille formatting, specifically in handling uppercase letters. The rules are as follows: Add a ":" before a single uppercase letter. :This is an :Example Add another ":" before multiple upperc ...

Troubleshoot: Why is my Google Chrome not playing videos? Uncover the solution with a

I have created a webpage with an HTML video tag that loads dynamically from a JSON file. I am currently using Chrome 50 for this project. The response is successful, and when inspecting the page using Chrome's developer tools, I can see the video tag ...

Can dynamic CSS imports be unloaded in a React application?

I am facing an issue with loading two files using react.lazy and suspense: import React, { Suspense, lazy } from "react"; import { Route, Redirect } from 'react-router-dom'; const MainLayout = lazy(() => import('Components/Layout/MainL ...

Struggling to make partial updates to a field within my CRUD update function

Currently, I am working on developing a CRUD application using NodeJS and Express to enhance my backend programming skills. The database being used for this project is MongoDB. This particular project serves as a back office for a shop without any frontend ...

Distinguishing between el and $el in Backbone.Js: What sets them apart?

I spent the entire afternoon struggling with this particular issue, but finally managed to resolve it. It ended up being a mix-up between assigning el and $el. Can anyone clarify the distinction between these two terms and provide guidance on when to use ...

React component not displaying dynamic content when extending from a class

Hey guys, I'm a newbie when it comes to React and I've encountered a problem with loading content fetched from an API. Usually, I use export default function About({ posts }) which works like a charm in loading my content. However, for one specif ...

"Exploring the power of Node.js by utilizing ObjectArray and implementing

Can I compare two arrays of objects in JavaScript? My goal is to find the common objects between these two arrays: First object array: [ { id_0: 356, name_0: 'xxxxx', id_1: 33, name_1: 'yyyyyy', id_ ...

I am looking to integrate my information into the user interface using Angular

import { Component, ViewEncapsulation } from '@angular/core'; import { Router } from '@angular/router'; import { Batch } from '../../../config/batchnew/batch.model'; import { BatchService } from '../../../config/batchnew ...

Connecting radio buttons to data in Vue using render/createElement

How do you connect the value of a selected radio button to a specific variable in the data object within a Vue application when using the render/createElement function? ...

Sending a form using an AngularJS dropdown menu

I have recently started using angularjs and decided to switch out a traditional html <select> box for an angular modal select box. The select box successfully populates with data from a $http ajax request, but I am facing issues with form submission ...

Displaying two distinct tables utilizing ng-repeat by employing customized directives

I'm facing an issue with a custom directive that generates tables and is appearing twice on my index page. The data for these tables comes from the $scope.globalrows variable. Even though globalrows contains 2 arrays, it always displays the second arr ...

Issue encountered while importing dependency in Cypress Cucumber framework

Currently facing an issue with importing certain dependencies in Cucumber. The error message I received is as follows: Running: features\my_feature.feature... (1 of 1) Browserslist: caniuse-lite is outdated. P ...

The following 13 error occurred in the node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js file

Every time I try to use the serialize function in my application on Next, it throws errors. Error - node_modules/next/dist/esm/server/web/spec-extension/cookies/serialize.js (40:0) @ parseCookieString Error - URI malformed I have attempted numerous soluti ...

generate a customized synopsis for users without storing any data in the database

In order to provide a summary of the user's choices without saving them to the database, I want to display it in a modal that has already been created. Despite finding some sources online, none of them have worked for me so far. Below is my HTML: &l ...

How come when you add ({}+{}) it equals to "[object Object][object Object]"?

I ran the following code: {}+{} = NaN; ({}+{}) = "[object Object][object Object]"; What is the reason behind the difference in result when adding ()? ...

What could be causing the issue preventing me from updating my SQL database through AJAX?

$(document).ready(function(){ $('.button').click(function(){ var clickBtnValue = $(this).val(); var ajaxurl = 'functions/delivered.php', data = {'action': clickBtnValue}; $.post(ajaxurl, da ...

Is it possible to convert ejs to jade?

I'm struggling with the conversion of this ejs code to jade: <h1>Iā€™m planning on counting up to <%= counter %></h1> <p><% for(var i = 1 ; i <= counter ; i++) { %> <%= i %>... <% } %></ ...

Exploring the power of async/await in conjunction with loops

My JavaScript code is designed to extract content from HTML pages and perform a crawling operation. However, the issue arises with asynchronous execution due to a request function. I attempted to utilize Promises and async & await to address this probl ...

"Webpack error: Including a comma within a string leads to a syntax problem when bund

I'm attempting to merge this file into my main JS. var constants = { height: 600, width: 400, default_bezier = "[ { \"startPoint\" : [51.6503017608354,203.464445873753], \"endPoint\" : [-52.41285540263849,202.372456432 ...

What is the process for transferring an image from the main page to another?

For days, I have been searching for an answer without any luck. It seems that I just can't wrap my head around it and apply it to what I am working on. Currently, I am using PHP to store images on the server when a user hits submit. My goal is to dis ...