"Retrieve objects from an array based on specified minimum and maximum values, while also checking for any null

My current dataset is structured as follows:

const data = [
  {
    id: '11se23-213',
    name: 'Data1',
    points: [
      { x: 5, y: 1.1 },
      { x: 6, y: 2.1 },
      { x: 7, y: 3.1 },
      { x: 8, y: 1.5 },
      { x: 9, y: 2.9 },
      { x: 10, y: 1.1 }
    ]
  },
  {
    id: 'fdsf-213',
    name: 'Data2',
    points: [
      { x: 5, y: 3.1 },
      { x: 6, y: 4.1 },
      { x: 7, y: 2.1 },
      { x: 8, y: 0.5 },
      { x: 9, y: 1.9 },
      { x: 10, y: 1.4 }
    ]
  },
]

I am currently working on rendering a chart based on this dataset and have specific objectives to achieve with it.

  • I need to filter the points using minimum and maximum values (provided by the user in input fields)
    • The user has the option to provide only the minimum value
    • The user has the option to provide only the maximum value
    • The user can provide both the minimum and maximum values
  • If the user removes or clears both the minimum and maximum values, the data should revert back to its original form.

Considering the requirements above, it is possible for the max and min values to be null.

As I am utilizing Angular for this task, below is the code snippet of what I have implemented so far along with the challenges I am facing:

component.ts

 const clonedData = data; // Keeping a clone for later reversion
 const mainData = data; // Data used for rendering and filtering

 // Utilizing Angular's reactive forms

 this.form.valueChanges.pipe(
   debounceTime(500),
   distinctUntilChanged(),
   tap(values => {
     if (values.min || values.max) {
       this.mainData = this.mainData.map(item => {
         return {
            ...item,
            points: items.points.filter(point => point.y >= values.min && point.y <= values.max)
         });
        return;
     }
     
     // Revert to original data if both values are empty
     this.mainData = this.clonedData;

   }).subscribe()

It is evident that there are some issues present in my code.

One major issue is that even when providing both minimum and maximum values or just one of them, the points array always returns empty.

On clearing or removing both values, the function appropriately reverts back to the default data (working as intended).

Answer №1

Check out this code snippet:

const newData = [
  {
    id: '11se23-213',
    name: 'Info1',
    numbers: [ { x: 5, y: 1.1 }, { x: 6, y: 2.1 }, { x: 7, y: 3.1 }, { x: 8, y: 1.5 }, { x: 9, y: 2.9 }, { x: 10, y: 1.1 } ]
  },
  {
    id: 'fdsf-213',
    name: 'Info2',
    numbers: [ { x: 5, y: 3.1 }, { x: 6, y: 4.1 }, { x: 7, y: 2.1 }, { x: 8, y: 0.5 }, { x: 9, y: 1.9 }, { x: 10, y: 1.4 } ]
  }
];

const filterData = (arr, min, max) => 
  arr.map(e => ({
    ...e,
    numbers: e.numbers.filter(({ y }) => (min === null || y >= min) && (max === null || y <= max))
  }));

console.log('min=1, max=2', filterData(newData, 1, 2));
console.log('min=null, max=2', filterData(newData, null, 2));
console.log('min=1, max=null', filterData(newData, 1, null));
console.log('min=null, max=null', filterData(newData, null, null));

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

The JSON object array is not empty, but it is unable to be iterated using a foreach loop, displaying a

Exploring a library of books from a Firestore collection in the create() method. The book data is stored in an array called checkout which is initialized in the data() method. export default { name: "checkout-history", data() { return { che ...

JavaScript: Implement a function that returns an object with key-value pairs instead of a

Once again, I'm looking at this particular answer. var firstEvents = events.reduce(function(ar, e) { var id = e.getId(); if (e.isRecurringEvent() && e.isAllDayEvent() && !ar.some(function(f) {return f.eventId == id})) { ar.pus ...

Is there a way to get a loop to continually execute another loop?

By running the following code, you can obtain a number close to pi. The program prompts the user to input the number of darts to be thrown per trial, which is then used to calculate an approximation of pi. I'm struggling to get the code to run for a s ...

Retrieve: Type 'string | undefined' does not match the parameter type 'RequestInfo'

When using the fetch function, I encountered an error with the "fetchUrl" argument: Error: Argument of type 'string | undefined' is not assignable to parameter of type 'RequestInfo'. This is the code snippet where the error occurred: ...

Processing XML Files Using Nodejs

Apologies for the rookie question, but I'm feeling a bit confused... I'm attempting to pull "objects" from an XML file so that I can modify and incorporate them into a database. I attempted using xml2js and now have a JavaScript object, but I&ap ...

Stopping autoplay in React Swiper when hovering over it

I'm currently struggling to find a way to pause the autoplay function on swiper when hovering over it. Despite my efforts, I have not been able to locate a solution. <Swiper spaceBetween={0} navigation={{ ...

Lightbox2 is looking to reposition the caption to the right of the image

Can anyone help me understand how to move the caption, found in data-title, from underneath an image to the right of the image? I'm not very familiar with HTML/CSS, but it looks like the image is enclosed within a div called .lb-outerContainer, and t ...

Tips for implementing a jQuery plugin on specific elements within an HTML page

I've been experimenting with the jQuery extension for searchable dropdowns available at this link. While I am impressed with its functionality, I'm looking to apply it selectively to specific elements on my webpage rather than all of them. Is the ...

How can I repeatedly execute a function with distinct inputs sourced from an API in Python?

I may have phrased the title incorrectly. I am interested in knowing if it is feasible to repeat a function for a specific input. Providing the code would simplify the explanation. Here is the provided code: from urllib.request import urlopen import json ...

What is the method to prevent the label from closing in the MUI 5 datepicker?

Is there a method to prevent the Material 5 Datepicker from closing when there's a label but no value? Current Scenario: Current Desired Outcome: Expected Sample Code: <LocalizationProvider dateAdapter={AdapterDayjs}> <DatePicker lab ...

Django views functions do not receive any data during execution

Things are running smoothly, but it appears that the post function in views.py is not receiving any data. Also, how can I create a submit button using pure JavaScript without reloading the page? views.py: from django.shortcuts import render from rest_frame ...

Creating an automatic image carousel using a combination of Jquery, Javascript, and CSS

I have been working on creating a slider using jQuery and javascript, but I am facing some issues with the autoplay functionality and the next-previous buttons. This slider is intended for displaying images as a title indicates. Can anyone assist me with i ...

Excessive recursion in MooTools causing issues with Google Maps integration

Hello, I'm currently facing an issue with my WordPress plugin. Whenever Mootools is included, Google Maps are not displaying due to "too much recursion" error. Here is a snippet of the code for reference: Any suggestions or workarounds for this incon ...

I'm puzzled as to why my get request seems to be hit-or-miss, working at times but returning a 404 not found error at other

Currently in the process of learning Angular and working on a project that involves a MongoDB database and Express for APIs. I am trying to retrieve comments for a specific post using the post ID. The GET request should return a list of comments, but the ...

Is "as" truly necessary in this context?

After following a tutorial, I created a class and noticed that the interface was declared with an as name. I'm wondering if this is necessary. What is the purpose of reassigning it when it was already assigned? My TypeScript code: import { Component ...

Issue with the successful execution of connection event handler in NodeJS and Socket.io?

When I look at my code in files named server.js and index.html, I notice that the io.on('connection') part is not executing the console.log method in its callback when I visit my server in the web browser. Take a look at the code snippets below ...

Can an inferred object type be imported in Flow?

Within a single file, I have the ability to include the following object: type NewType = { dateCreated: Date } export const myModel: NewType = { dateCreated: new Date() } I am particularly intrigued by the prospect of importing NewType alongside the impo ...

Challenges with jQuery Image Sliders

Currently, I am learning from a tutorial on creating a custom jQuery content slider and you can find the tutorial here. Everything is working smoothly in terms of creating the image slider. However, I am facing an issue where I want to have the 'Next ...

Two sets of buttons, however, one set is carrying out the incorrect function

I am trying to create two button sets that, when clicked, are supposed to angle the text below them at 45 degrees. However, I am facing an issue where both set 1 and set 2 only control the text linked to button 1. I need each button set to control their ...

Trigger an endless loop upon window.onload event

Every now and then, when a user opens the page, it starts flickering and resizing itself. After checking the log, it appears that the submit function is being called multiple times, but I can't reproduce this issue in my own environment. Is there som ...