sophisticated method for sorting through data within an array of arrays

How can data be filtered from an array of arrays?

Below is an example to help explain the process.

To filter the data, use startnumber and endnumber in the query.

const data =  [
{
  "name": "x",
  "points": [
    [100, 50, 1],        //[number, value, bit]       
    [150, 51, 0],
    [170, 52, 1],
    [200, 53, 0]
  ]
},
{
  "name": "y",
  "points": [
    [60, 50, 1],
    [100, 5, 1],
    [150, 6, 0],
    [170, 7, 1],
    [200, 53, 1]
  ]
},
{
  "name": "z",
  "points": [
    [300, 50, 1],
    [350, 51, 0],
    [370, 52, 1],
    [400, 53, 1]
  ]
}
]

// To find records with names x & y and numbers between 100 to 170

const names = ["x", "y"];
const startnumber = 100;
const endnumber = 170;

const finalResult= [];
for(const n of names){
  console.log('name', n);
  console.log('startnumber', startnumber)
  console.log('endnuumber', endnumber)
  const result = data.find(x=>x.name === n)
  
  // How can startnumber and endnumber be applied in the query above? Or is there another elegant solution?

  if(result){
    finalResult.push('result', result);
  }
}

if(finalResult.length){
  console.log(finalResult);
}

The expected result should be

[
  {
    "name": "x",
    "points": [
      [100, 50, 1],
      [150, 51, 0],
      [170, 52, 1],
    ]
  },
  {
    "name": "y",
    "points": [
      [100, 5, 1],
      [150, 6, 0],
      [170, 7, 1],
    ]
  }
]

Answer №1

const filteredResults = data.filter(elem => !!names.find(name => name == elem.name))

Explanation:

  1. data.filter is used to iterate through each element in the array data.
  2. names.find is applied to each element in the array names to find a matching value.
  3. The double negation (!!) is utilized since find returns an element, converting it into a boolean.
  4. The resulting array contains elements from data with names that match the values in names.

const data = [
{
  "name": "x",
  "points": [
    [100, 50, 1],
    [150, 51, 0],
    [170, 52, 1],
    [200, 53, 0]
  ]
},
{
  "name": "y",
  "points": [
    [60, 50, 1],
    [100, 5, 1],
    [150, 6, 0],
    [170, 7, 1],
    [200, 53, 1]
  ]
},
{
  "name": "y",
  "points": [
    [60, 50, 1],
    [200, 53, 1]
  ]
},
{
  "name": "z",
  "points": [
    [300, 50, 1],
    [350, 51, 0],
    [370, 52, 1],
    [400, 53, 1]
  ]
}
]

// Want to filter records with names 'x' and 'y', where number is between 100 and 170.

const names = ["x", "y"];
const startNumber = 100;
const endNumber = 170;

const filteredResults = data
  .filter(elem => !!names.find(name => name == elem.name))
  .map(elem => {
    return {
      name: elem.name,
      points: elem.points.filter(point => point[0] >= startNumber && point[0] <= endNumber)
    }
  })
  .filter(elem => elem.points.length > 0)

console.log(filteredResults)

Answer №2

This method offers a sophisticated approach:

const result = data.reduce((accumulator, current) => {
  const { title, values } = current
  const filteredValues = points.filter(value => value[0] >= startValue && value[0] <= endValue)
  return titles.includes(title) && filteredValues.length > 0 ? accumulator.concat({ title, values: filteredValues }) : accumulator
}, [])

Answer №3

When analyzing the task and the two provided data structures, it becomes apparent that a dual-layered filtering process is required for each data element.

  1. The first step involves identifying the data item based on its name (obtained from the additional names array).
  2. The second step entails filtering the points array of each data item to determine if the first element in the points array falls within a specified number range (defined by the supplementary startnumber and endnumber values).

Consequently, an effective strategy was to utilize the reduce function on the given data array with a reducer function that handles these two tasks for each data item.

The initial value for the reducer function serves as a configuration and collection object that includes...

  • A name lookup mechanism (implemented as a Map instance) for the specific data items to be processed.
  • The startnumber and endnumber range values designated as lowerNumber and upperNumber, respectively.
  • An array named result where only those data items meeting all criteria are stored.

function collectItemsByNameWhichHavePointsInNumberRange(collector, item) {
  const { nameLookup, lowerNumber, upperNumber, result } = collector;
  let { name, points } = item;

  // ... code snippet to gather items by name ...
  if (nameLookup.has(name)) {
    points = points
      .filter(([number]) =>
        (number >= lowerNumber) && (number <= upperNumber)
      );

    // ... filter out items with points falling within the defined number range ...

    if (points.length >= 1) {
      result
        .push({
          ...item,
          points,
        });
    }
  }
  return collector;
}

const data = [{
  name: "x",
  points: [
    [100, 50, 1],
    [150, 51, 0],
    [170, 52, 1],
    [200, 53, 0],
  ],
}, {
  name: "y",
  points: [
    [60, 50, 1],
    [100, 5, 1],
    [150, 6, 0],
    [170, 7, 1],
    [200, 53, 1],
  ],
}, {
  name: "z",
  points: [
    [300, 50, 1],
    [350, 51, 0],
    [370, 52, 1],
    [400, 53, 1],
  ],
}];

const names = ["x", "y"];
const startnumber = 100;
const endnumber = 170;

const { result } = data
  .reduce(collectItemsByNameWhichHavePointsInNumberRange, {
    nameLookup: new Map(names.map(value => [value, value])),
    lowerNumber: startnumber,
    upperNumber: endnumber,
    result: [],
  });

console.log({ result });
.as-console-wrapper { min-height: 100%!important; top: 0; }

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

"Transforming the Website Background with a Splash of Color

I am trying to figure out how to change the color scheme of my website with a button click. Currently, when I select a different color, only the background of the webpage I'm on changes, not the entire website. I have applied CSS but it's not ref ...

Is extracting the title of an image from Flickr?

I have a JavaScript code that randomly pulls single images from Flickr every time the page is refreshed. Now, I want to add a feature where the title of the image is displayed when it's hovered over. However, I've been searching for a solution fo ...

Embed the aspx file within the background-image attribute similar to how an image source is

Within my asp.net application, there is an image tag linking to another aspx file in the src attribute, displaying a picture. <img src="/picture.aspx?Param=3" alt="picture"/> I need to convert the image tag into a div with a background-image proper ...

Attempting to generate a cost estimator, however, no results are showing up upon clicking the calculate button

Having based my code on a template and being fairly new to Javascript, I expected everything to work smoothly. However, upon testing it, I encountered an issue where nothing was displayed in the results boxes. My goal is to develop a pricing calculator th ...

The process of merging these two functions involves ensuring that one function does not start until the other has successfully completed its task

A closer look at the two functions in question: const handleSubmit = async (e) => { e.preventDefault(); console.log(songLink) const newSong = { songName, songLink, userId }; const song = await dispatch(pos ...

Pass Form ID To Function In A Dynamic Way

I have multiple forms on my webpage and I want to use the same ajax function for all of them. It currently works well for one form by fetching the id with getElementById and then passing it to the ajax function. My goal is to dynamically pass down the form ...

Error: global not declared in the context of web3

I've been attempting to integrate Web3 into my Ionic v4 project for some time now. However, I keep encountering errors when I try to serve the project. Specifically, I receive an error message stating that Reference Error: global is not defined. Cre ...

Is it recommended to exclude the NGXS NgxsLoggerPluginModule for production deployments?

When developing, it's common to use the following imports: import { NgxsReduxDevtoolsPluginModule } from '@ngxs/devtools-plugin'; import { NgxsLoggerPluginModule } from '@ngxs/logger-plugin'; Is it recommended to remove these imp ...

Utilizing Visual Studio: Implementing jsmin in post-build actions

After attempting to add jsmin.exe as a post-build event in my VS 2010 project, I encountered an "error code 9009" when building the project. I tested this in the command prompt and found that it works if I navigate to the folder and run: jsmin < debug ...

Is it possible to create a personalized serialize form when sending an AJAX POST request

How can I format form data on an AJAX POST request differently than the default $("#formid").serialze()? The current result is not suitable for my needs, as it looks like this: `poststring="csrfmiddlewaretoken=bb9SOkN756QSgTbdJYDTvIz7KYtAdZ4A&colname= ...

Connection lost from JS client in Twilio's Programmable Chat

My React application utilizes the Twilio Programmable Chat library for chat functionality. The setup code typically appears as follows, enclosed within a try/catch block: this.accessManager = new AccessManager(twilioToken.token); const chatClientOptio ...

I have developed a function that adds up price values, but for some reason it is always lagging one step behind

I am facing an issue with my React container that has add and subtract functions. These functions are triggered whenever a user clicks on '+' or '-' spans, to calculate the total 'price' of three different 'products' ...

Learn how to utilize JavaScript produced by the `webpack output library` in a `nodejs` application

I'm currently utilizing webpack to bundle my JavaScript into a library that serves two purposes: one for browser usage and the other for integration into Node.js applications. Below is a snippet of my webpack configuration: output: { filename: ...

Utilizing the change function in conjunction with that

My attempt at creating a simple function to implement the change function didn't go as planned:/ What I am trying to achieve: 1- When a cost checkbox is checked, assign the corresponding cost (e.g., cost1.checked ? cost1 = 10 : 0) 2- Calculate and di ...

Distance Calculator for Geolocation WatchPosition

I am currently utilizing geolocation to track the user's current location and keep an eye on it using the watchPosition method. Is there a way to determine the distance between the starting position of the user and their current position? Here is the ...

Smoothly transition between the new and existing child elements in a React component with a

Currently, I am utilizing a React component that renders a child element through props.children. The content within this child element varies dynamically. I am looking for the most effective method to smoothly transition (fade out the old element and fad ...

Refresh a TextBox using an Ajax Response

Is there a way to dynamically update a textbox with the response from an ajax call? I've managed to get the response and assign it to the textbox using: document.getElementById("testPad").value = xmlHttpRequest.responseText; The issue is that the en ...

Angular: monitoring changes in HTML content within a Component or Directive

I have a situation where I am retrieving HTML content from a REST endpoint using a directive and inserting it into a div element using [innerHTML]. Once this HTML content is rendered, I would like to manipulate it by calling a global function. My approach ...

Audio waves visualization - silence is golden

I am attempting to create a volume meter, using the web audio API to create a pulsation effect with a sound file loaded in an <audio> element. The indicator effect is working well with this code; I am able to track volume changes from the playing aud ...

Value of type 'string' cannot be assigned to type '{ model: { nodes: []; links: []; }; }'

I am a beginner in TypeScript and I have added types to my project. However, I am encountering an error with one of the types related to the graph: Type 'string' is not assignable to type '{ model: { nodes: []; links: []; }; }'.ts(2322) ...