Angular 8: How to Filter an Array of Objects Using Multiple Conditions

I am faced with the following scenario where I need to filter an array of objects based on lineId, subFamily, and status.

My current code successfully filters based on lineId, but now I also need to include a condition for subFamilyId.

I have two specific conditions:

1) If the lineId is the same but the subfamily is different, both objects should be included in the result. For example - if there are two objects with lineId 2 but different subFamilies, both should be kept.

2) If the lineId is the same but the status is different (e.g. New and Submitted), only the object with the Submitted status should be kept. For example - if two objects have subfamily 03 and lineId 3 but different statuses, only the submitted status object should be included.

Can someone assist me in adding a condition for subFamilyId to my existing code?

Below is the sample response:

const data = [
    {
        "Subfamily": "01",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "02",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "03",
        "lineId": "3",
        "status": "Submitted"
    },
    {
        "Subfamily": "03",
        "lineId": "3",
        "status": "New"
    },
    {
        "Subfamily": "04",
        "lineId": "4",
        "status": "New"
    }
];

Expected Output

output  = [
    {
        "Subfamily": "01",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "02",
        "lineId": "2",
        "status": "Submitted"
    },
    {
        "Subfamily": "03",
        "lineId": "3",
        "status": "Submitted"
    },
    {
        "Subfamily": "04",
        "lineId": "4",
        "status": "New"
    }
];

Here is my current working code:

 removeDuplicatesObject(data){
    const uniqueResponse = data.reduce((acc, item) => {
      if (!acc[item.lineId] || item.status === "Submitted") {
        acc[item.lineId] = item;
      }
      return acc;
    }, {});
    const uniqueResponseArray = Object.values(uniqueResponse);
    return uniqueResponseArray;
  }

Any assistance on this matter would be greatly appreciated.

Answer №1

To group by the combination of Subfamily and lineId, filtering out objects that do not have a status of "Submitted".

const
    data = [{ Subfamily: "01", lineId: "2", status: "Submitted" }, { Subfamily: "02", lineId: "2", status: "Submitted" }, { Subfamily: "03", lineId: "3", status: "Submitted" }, { Subfamily: "03", lineId: "3", status: "New" }, { Subfamily: "04", lineId: "4", status: "New" }],
    result = Object.values(data.reduce((r, o) => {
        const key = ['Subfamily', 'lineId'].map(k => o[k]).join('|');
        if (!r[key] || o.status === 'Submitted') r[key] = o;
        return r;
    }, {}));

console.log(result);
.as-console-wrapper { max-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

Error message: Could not locate the class 'NunoMaduroCollisionAdaptersLaravelCollisionServiceProvider'

Encountering an error while attempting to install Composer in a Laravel project. Error message: Illuminate\Foundation\ComposerScripts::postAutoloadDump @php artisan package:discover In ProviderRepository.php line 208: Class 'NunoMadur ...

Having trouble deploying a Heroku app using Hyper? Here's a step-by-step guide to

After running the following commands: https://i.stack.imgur.com/WZN35.png I encountered the following errors: error: src refspec main does not match any error: failed to push some refs to 'https://git.heroku.com/young-brook-98064.git' Can anyon ...

Switch up the link color when it pops up

Is there a method to change the link color to gray without encountering glitches like on my site, where it mistakenly shows "Quick Nav."? Click here to view the page with the glitch I only want this particular link to be bold and not any other links. He ...

Utilizing Nicknames in a JavaScript Function

I'm dealing with a function that is responsible for constructing URLs using relative paths like ../../assets/images/content/recipe/. My goal is to replace the ../../assets/images section with a Vite alias, but I'm facing some challenges. Let me ...

Extending fabric.js toObject with custom properties can result in the loss of default properties

After doing extensive research on various platforms, including this one, I am still struggling to get everything working as desired. My main goal is to save custom properties in all shapes, specifically the uuid and rt_attributes. Following the manual, I ...

Reveal hidden elements once the form has been submitted

At this moment, the info, stat and foo elements are hidden. Strangely, when I submit the form, they don't become visible. However, if I incorporate the unhide() function within the <button onclick="unhide()"></button>, it works p ...

Changes in the styles of one component can impact the appearance of other

When it comes to styling my login page, I have specific stylesheets that I include in login.component.ts. For all the common CSS files, I have added them in the root index ("index.html") using the traditional method. However, after a user logs into the sys ...

What is the process of setting up a subelement in a Vue array?

I am currently working on incorporating an array read feature using Vue.js: {{ this.locations[this.record.carton.LocationID - 1].Location }} Although the code functions properly during runtime, it throws an error upon initial loading: app.js:55125 [Vue wa ...

In order to develop a JS class in React JS, I must import Scripts

I have a collection of SDK scripts that need to be included in the following manner: <script src="../libs/async.min.js"></script> <script src="../libs/es6-shim.js"></script> <script src="../libs/websdk.client.bundle.min.js ...

Guidelines for implementing more rigorous type checks in TypeScript:

I am looking to enhance the code validation process and eliminate any implicit 'any' types. To achieve this, I have set "strict": true in my tsconfig.json. { "compilerOptions": { "target": "ES5", ...

When invoked, a Javascript Object comes back empty

My code snippet: const channels = fauna.paginate(q.Match(q.Index("channels"), "true")) // Query FaunaDB database for channel list => create constant called users containing results const channelList = channels.each(function (page) { ...

Strategies for effectively searching and filtering nested arrays

I'm facing a challenge with filtering an array of objects based on a nested property and a search term. Here is a sample array: let items = [ { category: 15, label: "Components", value: "a614741f-7d4b-4b33-91b7-89a0ef96a0 ...

Incorporate JQuery into your NodeJS project by leveraging the existing minified file

Can we integrate JQuery into Node.js and make JQuery AJAX calls without altering the syntax by using a pre-downloaded minimized JQuery file? To clarify, I have the minified file and wish to incorporate it into Node.js in this manner: var jquery = require( ...

How can I trigger the rendering of a component by clicking a button in a separate component?

I am currently facing a challenge in rendering a component with an "Edit" button that is nested within the component. I attempted to use conditional rendering in my code, but unfortunately, I am struggling to make it work as expected. Does anyone have any ...

Changing the name of '_next' to 'next' within the output folder: NextJS

While developing my NextJS chrome extension, I encountered an issue when trying to 'load unpacked' extension. An error message popped up stating that "Cannot load extension with file or directory name _next. Filenames starting with _ are reserved ...

Incorporating a unique variant with Tailwind called "

I'm currently struggling with inputting the configuration file for Tailwind. Despite my efforts, I cannot seem to get it right. The code appears correct to me, but I am unsure of what mistake I might be making. Below is the snippet of my code: import ...

Unable to retrieve the path during an AJAX request in PHP and JavaScript

I'm struggling with passing data to the server-side using an ajax call. It's giving me an error saying 'The required path not found'. I am working with CodeIgniter for the MVC framework. Below is a snippet of the code: var url = "http: ...

JavaScript and HTML have encountered an Uncaught TypeError: The property 'addEventListener' cannot be read because it is null

Having an issue here. Whenever I try to play sound from an image, I encounter an error. Uncaught TypeError: Cannot read property 'addEventListener' of null Here is my HTML code: <html> <head> <title>Music</title> < ...

Leveraging Javascript Modules within a Typescript Vue Application

The issue at hand I've encountered a problem while attempting to integrate https://github.com/moonwave99/fretboard.js into my Vue project. My initial approach involved importing the module into a component as shown below: <template> <div&g ...

"Placing drop-down animations in just the right spot

I'm currently working on adjusting the dropdown behavior for thumbnails when hovering over them. I want the drop-down to appear beneath the 'Caption Title' instead of above the image, but so far my CSS adjustments haven't been successfu ...