Key steps for effectively implementing a Substring-Filter on a JSON array in d3

Trying to apply filtering on a JSON data array structured like this:

var data = [
    {
        "key": "FirstGroup",
        "color": "#1f77b4",
        "values": [
            {
                "label": "PWY-6089",
                "value": 0.0
            },
            {
                "label": "TOLSULFDEG-PWY",
                "value": 0.0
            },
           
        ]
    },
    {
        "key": "SecondGroup",
        "color": "#78bf00",
        "values": [
            
            {
                "label": "PWY-4101",
                "value": 0.3
            },
            {
                "label": "PWY0-1356",
                "value": 0.5
            }
        ]
    },
    ...
]

The goal is to have a subset of stackedChartData in filteredData where the filterString is found as a substring within "label". This is the proposed method:

function startsWith(str, word) {
  return str.lastIndexOf(word, 0) === 0;
}
function filterData() {
  input = document.getElementById('filterInput');
  filterString = input.value;
  
  var filteredData = stackedChartData.filter(function (entry) {
        entry.values.forEach(element => {
        
         return startsWith(element.label,filterString);
            
        }); 
  });

 console.log(filteredData,"filteredData");
  
}

Due to issues with String.startsWith(), the startsWith() function was used instead in the script. Despite correct definitions for filterString and element.label, the filteredData remains empty. Any guidance on rectifying this confusion would be greatly appreciated. Best regards.

Answer №1

Challenge

The for loop is simply iterating through the data without returning anything.

Resolution

To obtain the filtered data, utilize the array methods filter and find.

Detailed Explanation (refer to code snippet below)

  1. filter - Used to retrieve 2 out of 3 objects
  2. find - Returns immediately when condition 'startsWith' is met

Refer to the following code example:

let information = [{
    "key": "FirstSet",
    "color": "#1f77b4",
    "values": [{
        "label": "PWY-6089",
        "value": 0
      },
      {
        "label": "TOLSULFDEG-PWY",
        "value": 0
      }
    ]
  },
  {
    "key": "SecondSet",
    "color": "#78bf00",
    "values": [{
        "label": "PWY-4101",
        "value": 0.3
      },
      {
        "label": "PWY0-1356",
        "value": 0.5
      }
    ]
  },
  {
    "key": "ThirdSet",
    "color": "#d62728",
    "values": [{
        "label": "PWY-4101",
        "value": 1
      },
      {
        "label": "PWY0-1356",
        "value": 1
      }
    ]
  }
]

let filteredInformation = information.filter(element =>
  element.values.find(valueElement =>
    valueElement.label.startsWith('PWY-41') // User can input string here
  )
)

console.log(filteredInformation)

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

Using a key as an argument in the `map` function invocation

I keep getting a warning message stating that each child in the array does not have a unique key. const ITEMS = [ { "name": "apple", displayName: "Apple" "name": "orange", displayName: "Orange" }, { "name": "banana", di ...

AngularJS - development of a service entity

After deliberating between posting in the Angular mailing list or seeking assistance from the JavaScript community, I have decided that this is more of a JavaScript question. Hopefully, the knowledgeable individuals on Stack Overflow can provide a quicker ...

Executing a Node.js HTTP GET request is a breeze

I've encountered an issue while attempting to send an HTTP GET request using Node.js. The request to '/path/to/file?query=string' has failed with the error message: read ECONNRESET Any suggestions on how I can resolve this problem? Thank ...

Having issues with D3js chart rendering: Unable to display bars or pie chart properly, only shows as

I've been delving into D3js and I'm encountering an issue with the script below. It's only generating an SVG with a vertical line, and I'm struggling to figure out why. Within my data item called Fight, there is a property that gathers ...

What is the correct way to pass parameters when using the setState() function in React hooks?

I am working on a project where I have a list of country names. When a user clicks on one of the countries, I want to update the state with the name of the newly selected country. This state change will then trigger other changes in a useEffect(). The stat ...

looping through the multi-dimensional array using v-for

Interested in using v-for and I have encountered a scenario with an object structure as seen here: https://i.sstatic.net/wNguk.png Upon inspecting the dev console, the object looks similar to this: https://i.sstatic.net/jyqth.png My query is about how to ...

"Using conditional statements to check for specific value ranges and properly handling cases where the result is undefined

Currently, I am working on a function that prompts the user to input a number and then displays a calculated score after they click a button. The score is based on the value entered by the user. While constructing this feature, I have pondered whether IF ...

Error in identifying child element using class name

I need help accessing the element with the class "hs-input" within this structure: <div class = "hbspt-form".......> <form ....class="hs-form stacked"> <div class = "hs_firstname field hs-form-field"...> <div class = ...

What is the best way to transfer data from form input fields to a script with AJAX and jQuery?

Here is the current structure of my code. Main File: index.php <script type="text/javascript" src="jquery-1.4.2.js"></script> <script type="text/javascript" src="ajax.js"></script> <select id="dropdown_id"> <option valu ...

Transform a string dictionary into dictionary notation

I'm currently facing an issue where I need to convert a string value into Dictionary format while respecting a specific syntax. However, when attempting to do so, I encounter an error. It seems that the json.load function is converting nested brackets ...

Creating a dynamic drag-and-drop layout in React using react-grid-layout

Utilizing the react-grid-layout package for implementing drag-drop and resize components, I have successfully achieved the functionality outlined in the documentation. Description of My Issue My challenge lies in creating a dynamic UI where the layout is ...

Caution: It is important for each child within a list to have a distinct "key" prop when using react-input

I'm currently facing an issue with the following code snippet: {array.map((item) => ( <> <input key={item.id} type="checkbox" /> ...

Exploring innovative designs for asynchronous JavaScript programming

Imagine you have an Express app and you need to retrieve data from a database to display on the frontend. There's a function in your code that looks like this (using node-mysql for handling database queries) exports.getData = function() { ...

Cross-Origin Resource Sharing problem: "Preflight request response does not meet access control criteria"

I'm currently tackling a Vue.js/Nuxt.js project that involves sending API requests to 'https://app.arianlist.com'. However, I've encountered some CORS challenges and came across this error message: "Access to XMLHttpRequest at &ap ...

Is there a way for me to retrieve the values of <td name="pname"> when the Edit button is

When the button is clicked, I use jQuery to add items in a td that I have created. $("#ddproduct").click(function () { $('#prodcuttable tr:last').after('<tr><td name="pname">' + prodName + '</td> <t ...

Implementing specific actions based on user selections in an Oracle APEX navigation bar

Within the application's navigation bar, there is a Home item that is present on all pages. I want to implement a feature where if the user clicks on the Home item, a warning message will pop up based on the page number, alerting them that any unsaved ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

Updating a document using the nano module in CouchDB is not supported

I am currently utilizing the Node.js module known as nano Why is it that I am unable to update my document? I need to set crazy: true and then change it back to false. This is the code I have: var nano = require('nano')('http://localhost ...

Unable to successfully update DIV content in JavaScript due to incorrect file path specified

I came across this code online and it seems to be functioning properly. However, no matter what name I give the file that is supposed to load into the DIV, I consistently receive an error message stating "Object was not found." What specific steps do I nee ...

Using Jquery colorbox to redirect or forward within the current colorbox container

I am facing a challenge with a colorbox that is currently loaded. I am looking for a way to redirect or forward to another page within the existing colorbox. window.location = href; does not seem to be effective in this situation. EDIT: To be more precis ...