Data filtration - techniques for removing unnecessary information in JavaScript

I have a JSON file containing data that requires filtering.

Here is an example structure of the JSON:

[{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", D:"FlightData"}]

I am currently utilizing the 'group by' method.

 function groupBy(list, keyGetter) {
        const map = new Map();
        list.forEach((item) => {
            const key = keyGetter(item);
            const collection = map.get(key);
            if (!collection) {
                map.set(key, [item]);
            } else {
                collection.push(item);
            }
        });
        return map;
    }

Initial grouping is done based on either A or B into Arrays

A is [[C],[D]] and B is[[C],[D]]

In cases where the data does not contain either C or D, the group needs to be removed as the data is irrelevant.

 for (let value of s1) {

           // A or B
          const routeGrouped = groupBy(PriceArrayFinal, route =>
                   route.FinalArrival);



            for (let origin of s3) {

          // C or D 
         const originGrouped = groupBy(routeGrouped.get(value), route =>

                     route.FirstDepartCityName);


Is it possible to delete the entire group such as A: [ [C], [] ] if either C or D is missing? If there is an empty array, the A or B group needs to be removed?

EDIT: Desired Output: All groups of A or B must include both C and D


[{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"}] 

 [ [ [Array], [Array] ], [ [Array], [Array] ], [ [Array], [Array] ], [ [Array], [Array] ] ]

Answer №1

To retrieve all the elements that have values for both C and D, you can utilize the filter method in JavaScript like shown below:

let input=[{A:"data",C:"flightData",D:"FlightData"},{B:"data",C:"flightData",D:"FlightData"},{A:"data",C:"flightData",D:"FlightData"},{B:"data",C:"flightData"},{A:"data",C:"flightData",D:"FlightData"},{B:"data",D:"FlightData"}];

let output = input.filter(({ C, D }) => C && D);

console.log(output)

Answer №2

To filter the Array, use the method filter().

const arr = [{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData"},
{A:"data", C:"flightData", D:"FlightData"},
{B:"data", D:"FlightData"}];

const result = arr.filter(a => { 
 return (a.hasOwnProperty('A') || a.hasOwnProperty('B') && a.hasOwnProperty('C') && a.hasOwnProperty('D'));
});


console.log(result);
/* Expected Output:
[{A:"data", C:"flightData", D:"FlightData"},
{B:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"},
{A:"data", C:"flightData", D:"FlightData"}] 
*/

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

Initiating a click function for hyperlink navigation

Here is the HTML and JavaScript code that I am currently working with: <!DOCTYPE html> <html> <head> <script src="http://code.jquery.com/jquery-3.3.1.min.js"></script> </head> <body> <a href="#f ...

Interactive data visualization with hover-over details

I am utilizing datamaps to showcase the countries of the world, however, I want the graph to be centered. The issue arises when I hover over a country and the pop up appears all the way to the left, aligned with where the country would be if it wasn't ...

Preventing access to websites through a web application using JavaScript

I am in the process of creating a web application that enables users to create a list of websites they wish to block, preventing access from their browsers. My goal is to block websites on all browsers, but I have narrowed my focus to Chrome for now. I ha ...

Make changes to external CSS using HTML and JavaScript

Is it possible to dynamically change the value of a background in an external CSS file using JavaScript? Currently, all my pages are connected to a CSS file that controls the background for each page. I am attempting to modify the background by clicking a ...

Grasping the idea of elevating state in React

I can't figure out why the setPostList([...postList, post]) is not working as expected in my code. My attempts to lift the state up have failed. What could be causing this issue? The postList array doesn't seem to be updating properly. I'v ...

When attempting to run npm run build for a Next.js application on an EC2 instance, it unexpectedly terminates on its own

While attempting to deploy my Next.js app on EC2, I encountered an issue where the npm run build command was being automatically killed. Suspecting it may be due to insufficient RAM, I switched to an instance type with 4GB of RAM (t3.medium), but the probl ...

Error: The configuration property is not defined, causing a TypeError at Class.run ~/node_modules/angular-cli/tasks/serve.js on line 22

I'm encountering a persistent error on my production server that indicates a missing angular.json file, even though the file is present in the root of my project! Every time I run npm start, npm build, or npm test, I receive the same error message. ...

Is it possible to send an HTTP request from the renderer process to the main process in Electron?

Currently, I am in the midst of developing an electron video player project. My main objective is to stream video from a readable stream to an HTML video-tag. I am exploring different solutions and strategies to achieve this goal. In particular, I am cur ...

Generating a JSON response with Jade templating

After going back to basics, I've been attempting to create a straightforward example involving calling a REST API, receiving JSON data in return, and then rendering that data in HTML using Jade. Despite my efforts, I have not been able to get any of ...

Display/hide a div containing distinct content

Upon clicking an image in the carousel, a position: absolute; div should appear containing two different images and a form related to the initial picture clicked with a submit button. How can I implement a show/hide feature that displays unique content for ...

The issue lies in the fact that the multiple route files are not correctly directing to the absolute path. Instead of navigating to the full path, they are simply adding new paths

Whenever I attempt to access files alternatively from two different routes, an error occurs (stating "Cannot GET /user/user/viewUser"). Here is the scenario: app.js file var home = require('./routes/index'); app.use('/', home); va ...

What is the process for setting a personalized title for error pages in Remix?

I'm currently working on setting up the 404 page for my Remix app, but I'm facing challenges when it comes to configuring the <title> meta tag for these pages. Within my root.tsx file, I have defined a MetaFunction and a CatchBoundary: exp ...

Unable to properly display the message in Angular

<!DOCTYPE html> <html ng-app> <head> <script data-require="angular.js@*" data-semver="1.4.3" src="https://code.angularjs.org/1.4.3/angular.js"></script> <link rel="stylesheet" href="style.css" /> ...

Approach for calculating the total of values during an iteration

I am working with the array $scope.otherDetailsData [0] object amount: 29.9 code: "012" currency: "BRL" payedDate: "2016-11-10" roDate: "2016-08-01" type:"OTHER" [1] object amount: 39.9 code: "013" currency: "BRL" payedDate: "2016-11-11" roDate: "2016- ...

Shuffle letters in a word when hovered over, then unscramble them back to their original order

I have noticed a fascinating effect on several websites. To give you an idea, here are two websites that showcase this effect: Locomotive and TUX. Locomotive is particularly interesting to look at as the desired effect can be seen immediately when hovering ...

What exactly is a doclet as defined in JSDoc documentation?

//Sample 1 /** * Here we have a simple function that returns a message * @param {String} msg The message to be returned * @returns {String} The message */ function showMessage(msg) { return msg } //Sample 2 /** * This is a function that also retur ...

How come the error message in AngularJS is appearing as blank during error handling?

When utilizing AngularJS code to send a request to the server, everything works smoothly on success. However, deliberately redirecting the request to a different domain causes the CORS problem where the error handling function is triggered but errorData ...

Detecting and removing any duplicate entries in an array, then continually updating and storing the modified array in localstorage using JavaScript

I'm facing an issue with the function I have for pushing data into an array and saving it in local storage. The problem is that the function adds the data to the array/local storage even if the same profileID already exists. I want a solution that che ...

Switch over to TypeScript - combining Socket.IO, Angular, and Node.js

This is the code I'm using for my node server: import http from 'http'; import Debug from 'debug'; import socketio, { Server } from 'socket.io'; import app from './app'; import ServerGlobal from './serve ...

displaying a post-end issue on the express server

Currently, I am working on a school project that requires the development of a client-server application. The specific task is to create a webshop that can load products using AJAX. To achieve this, I am utilizing jquery and the $.load() method. Within my ...