Group the JSON data in JavaScript by applying a filter

I have a specific json object structure with keys cgi, tag and name, where the cgi key may be repeated in multiple objects. If any cgi has the tag 'revert', then that particular cgi should not be returned.

[
  {
    "cgi": "abc-123",
    "tag": "revert",
    "name": "Piyush"
  },
  {
    "cgi": "abc-123",
    "tag": null,
    "name": "Piyush"
  },
  {
    "cgi": "abc-456",
    "tag": null,
    "name": "Piyush"
  },
  {
    "cgi": "abc-789",
    "tag": null,
    "name": "Piyush"
  }
]

Therefore, only the following objects will be included in the output:

[
  {
    "cgi": "abc-456",
    "tag": null,
    "name": "Piyush"
  },
  {
    "cgi": "abc-789",
    "tag": null,
    "name": "Piyush"
  }
]

My attempt using filter method was unsuccessful as it did not yield the desired result.

Answer №1

If you want to collect all reversed cgi values, you can utilize the reduce() method. Following that, you can eliminate unwanted values by using the filter() method based on this collection.

*Instead of utilizing a Set, you could alternatively opt for an array. I chose a Set to prevent duplicates.

const data = [{"cgi":"abc-123","tag":"revert","name":"Piyush"},{"cgi":"abc-123","tag":null,"name":"Piyush"},{"cgi":"abc-456","tag":null,"name":"Piyush"},{"cgi":"abc-789","tag":null,"name":"Piyush"}];

// Retrieve all `cgi` values where the tag is `revert`.
const revertedTags = data.reduce((acc, item) => {
  if(item.tag === 'revert') {
    acc.add(item.cgi);
  }

  return acc;
}, new Set());

// Exclude elements present in the `revertedTags` collection.
const filteredTags = data.filter((item) => !revertedTags.has(item.cgi));

// Output result.
console.log(filteredTags);

Answer №2

Here's a handy one-liner tip: leverage a memoized function as a filter to sift through your items:

const data = [{"cgi":"abc-123","tag":"revert","name":"Piyush"},{"cgi":"abc-123","tag":null,"name":"Piyush"},{"cgi":"abc-456","tag":null,"name":"Piyush"},{"cgi":"abc-789","tag":null,"name":"Piyush"}];

const filteredTags = data.filter((map => e => map[e.cgi] ??= !data.find(e2 => e2.tag === 'revert' && e.cgi === e2.cgi))({}));

console.log(filteredTags);

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

An error occurred stating: "The require function is not defined in AngularJS and nodeJS."

I have searched through various similar questions here on SO, but none seem to provide a solution that fits my specific case. I am relatively new to using angularjs and nodejs, and I am encountering an issue that has me stuck. My goal is to save the input ...

Can you explain the varying methods of importing material-ui components and how they differ from each other?

After delving into the documentation for material-ui and exploring various online resources, it appears that there are multiple methods for importing the same component: import TextField from 'material-ui/TextField'; // or import TextField from ...

Is it possible for Node.js to not automatically restart the server when modifying .js files?

Right now I have node-supervisor set up to detect changes in .js files, and while it works well, I've realized that it restarts the server every time a js file is saved. Is there a way to save a server-side .js file without triggering a server restart ...

Ways to conceal a grid item in Material UI framework

My goal is to hide a specific grid item for a product and smoothly slide the others in its place. Currently, I am using the display:none property but it hides the item instantly. I have already filtered the products and now I want to animate the hiding of ...

Creating interactive avatars with Material UI and React to provide a dynamic user

I have developed a simple form validation application using react.js. Each user has a unique profile containing their personal information. I am looking to utilize the first letter of the user's name, for example Peter, where the letter "P" would be d ...

Show the cell data when the checkbox next to it is selected

I have a specific table setup and I am trying to display the content of the table cell if its corresponding checkbox is checked upon clicking a button. For example: If Row2 is checked, an alert box should display Row2 Below is my code snippet, Java ...

The Static Interface Binding in TypeScript

I have inquired about how to extend the static functionality of existing objects in JavaScript (using TypeScript). In all examples provided here, I am utilizing Object The code below showcases a polyfill definition for ECMAScript's Object.is function ...

Conditional jQuery actions based on the selected radio button - utilizing if/else statements

This task seemed simple at first, but I quickly realized it's more challenging than expected. Apologies in advance, as Javascript is not my strong suit. My goal is to have the main button (Get Your New Rate) perform different actions based on whether ...

The onchange event for the input type=file is failing to trigger on Google Chrome and Firefox

Update: Solved: http://jsfiddle.net/TmUmG/230/ Original question: I am facing an issue with handling image/logo upload alongside a hidden input type=file: <form class="image fit" id="theuploadform"> <input title="click me to chan ...

Conflicting Angular components: Sorting tables and dragging/dropping table rows

In the current project I'm working on, I've integrated both angular table-sort and angular drag-drop. However, I ran into an issue where dragging a row and attempting to drop it onto another row causes the table sort to forcefully rearrange the r ...

Parse the contents of a JSON file and elegantly format it, then Save the beautifully

I am struggling with parsing a nested JSON text file which appears as one long line in the file. Can someone guide me on how to read this file using Python and format it with proper indentation, then save it to a separate text file? ...

Having trouble accessing data beyond the login page using Node/Express

Currently in an unusual situation. I am developing a backend and frontend that connects to a third-party RESTFUL API managing some hardware. The third-party API is hosted on your local system as a webserver, meaning HTTP requests are directed to "localhost ...

Importing modules using relative paths results in failure due to module not being found, whereas employing absolute paths

I have been encountering this problem for a considerable amount of time and have made multiple attempts to resolve it. I am currently working on the development of my discord.js bot and recently switched from TS back to JS due to certain complications I fa ...

Automatically execute JavaScript upon loading the page with the option to value run on

Upon loading the page, Week 1 is automatically selected which is great. However, the javascript function only runs when I manually choose an option. I want the javascript to automatically trigger for week 1 without needing manual selection. Any ideas on ...

Angular and Firefox are flagging the response from my OAuth call as incorrect, however, Fiddler is showing a different result

Currently, I am in the process of developing a Cordova application and require OAuth authentication with my Drupal backend. My main issue lies in obtaining a request token for this purpose. Despite receiving a 200 response indicating success, when inspecti ...

When using JSON.stringify on a map object, it returns an empty result

var map1= new Map(); map1.set("one",1); var map2 = new Map(); map2.set("two",2); concatMap = {}; concatMap['one']= map1; concatMap['two']= map2; JSON.stringify(concatMap); //outputs : "{"one":{},"two":{}}" I als ...

Unveiling the Secrets of AJAX Requests with Enigmatic Strings Attached to URLs

My goal is to keep track of cricket scores on scorespro/cricket by utilizing browser AJAX requests. By analyzing the network traffic in Google Chrome, I have noticed that my browser sends out requests in this format: Whenever I click on the response withi ...

Exploring Symfony2: Enhancing user experience with dynamic form submission and dropdown menu updates

Starting from the beginning. I have a tab-panned layout with links. Upon clicking a link, a drop-down checkbox form is injected directly into the HTML through $(".dropdown-toggle").click(function() { var projectId = $("#permission-form").attr("data-p ...

Using Laravel to set cookies with Ajax

I am facing difficulties in setting cookies through laravel using ajax. Despite reading several questions and posts, I have not been able to find a solution. My issue involves a dropdown that triggers a javascript function to send its value to a controlle ...

How does the onclick event trigger even without physically clicking the button?

I am struggling with creating a simple button using mui. My intention is to activate a function only when the button is clicked, but for some reason, as soon as I enter the webpage, it triggers an alert automatically. This behavior is puzzling to me and ...