What is the best way to sort items by their properties?

Seeking to optimize the code by using a filter instead of lodash _forEach. However, the current filter code is not producing the desired result. Any insights on what might be incorrectly implemented here?

main.js


                const response = [];
                const data = [{
                        "isBrand": true,
                        "drugName": "Lipitor",
                        "specialtyPrice": {}
                    },
                    {
                        "isBrand": false,
                        "drugName": "Atorvastatin Calcium",
                        "drugStrength": "80mg",
                        "drugForm": "Tablet",
                        "mailPrice": {
                            "totalQuantity": 90,
                            "rejectMessage": [{
                                "settlementCode": "99",
                                "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                            }]
                        },
                        "retailPrice": {
                            "totalQuantity": 30,
                            "rejectMessage": [{
                                "settlementCode": "99",
                                "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
                            }]
                        },
                        "specialtyPrice": {}
                    }
                ];
                _.forEach(data, function(drug) {
                    if (drug.retailPrice !== undefined || drug.mailPrice !== undefined) {
                        response.push(drug);
                    }
                });

                const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

                console.log(filterItems);

            
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

Expected Outcome

[{
        "isBrand": false,
        "drugName": "Atorvastatin Calcium",
        "drugStrength": "80mg",
        "drugForm": "Tablet",
        "mailPrice": {
            "totalQuantity": 90,
            "rejectMessage": [{
                "settlementCode": "99",
                "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
            }]
        },
        "retailPrice": {
            "totalQuantity": 30,
            "rejectMessage": [{
                "settlementCode": "99",
                "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
            }]
        },
        "specialtyPrice": {}
    }
];

Answer №1

Trying this out.

const checkObjectNotEmpty = function(obj){
    return Object.keys(obj).length > 0;
},
checkObjectHasPrice = function(obj){
    return obj.hasOwnProperty("mailPrice") && obj.hasOwnProperty("retailPrice");
};


const filteredItems = data.filter( item => return checkObjectHasPrice(item) && checkObjectNotEmpty(item.mailPrice) && checkObjectNotEmpty(item.retailPrice);

Answer №2

You can use the Array.forEach method in JavaScript like so:

data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)

This implementation would appear as follows:

const response = [];
const data = [{
    "isBrand": true,
    "drugName": "Lipitor",
    "specialtyPrice": {}
  },
  {
    "isBrand": false,
    "drugName": "Atorvastatin Calcium",
    "drugStrength": "80mg",
    "drugForm": "Tablet",
    "mailPrice": {
      "totalQuantity": 90,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "retailPrice": {
      "totalQuantity": 30,
      "rejectMessage": [{
        "settlementCode": "99",
        "settlementDesc": "Sorry, the system is temporarily:Lo sentimos,Intente(Código de error 85)"
      }]
    },
    "specialtyPrice": {}
  }
];

data.forEach(d => (d.retailPrice || d.mailPrice) ? response.push(d) : null)

const filterItems = data.filter(item => item.retailPrice && item.mailPrice)

console.log(filterItems);

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

Retrieve the webpage address, search parameters, and anchor symbols

I have a form input where users enter a valid URL. My goal is to extract the URL, query string (if provided by the user), and hash value (if provided) separately. This is what I currently have: var url = userInput.split('?')[0]; //get url v ...

What are the steps to adjust the size of a browser window in WebDriverJS?

Currently, I am utilizing WebDriverJS, the JavaScript bindings for WebDriver, to conduct basic frontend testing (powered by nodejs). Nevertheless, encountering challenges resizing the window and the documentation available appears somewhat unclear in my u ...

Stop MatDialog from closing automatically when clicked outside while there are unsaved changes

Is there a way to prevent closing when there are pending changes without success? this.dialogRef.beforeClosed().subscribe(() => { this.dialogRef.close(false); //some code logic //... }); The setting disableClose on MatDialog must remain as false ...

When reaching the third section, the scrolling will stop at 100% of the viewport height

Can someone help me figure out why my scrolling function is stopping at the third section and not continuing to the last one? I've included the code snippet below for reference: <div class="body" data-spy="scroll" data-target=".navbar-fixed- ...

Learn how to properly display the state array within a React component. Even though the array is present in the state, you may encounter issues where it

I am facing an issue while trying to display data from firestore in my React component. I have updated the global state array with the firestore data and it is being updated, but when I try to render that array, it shows as undefined. Initially, I attempt ...

PHP code snippet to duplicate an array in PHP

Having a problem when trying to copy an array into another array in PHP and then outputting it as JSON. The issue is that it only duplicates the last element in the array multiple times. Any guidance on where I might be making a mistake would be greatly ap ...

How can we determine clicks or touches reliably across desktop and mobile platforms?

While working on my recent Android phone using Chrome, I noticed that subscribing to the click event on a button element only triggers when tapping the button, not when holding it down and then releasing. In order to trigger an action when the button is re ...

Ensuring an element matches the height of its child using CSS styling

How can I ensure that the parent element's height adjusts to match the height of its child element using CSS? <div class = "parent"> <div class="child"> </div> </div> ...

npm package.json scripts not executing

Whenever I try to run npm start or npm run customScriptCommand, npm seems to not be executing anything on my project and just quickly returns a new line in the terminal. I attempted to solve this issue by uninstalling node and npm from my machine, then in ...

How can I retrieve the chosen value from an AJAX combobox using JavaScript in an ASP.NET C# application?

How can I retrieve the selected value from an AJAX combobox item using JavaScript in ASP.NET C#? Below is the code snippet: <asp:ComboBox ID="dropdown_dest" runat="server" Width="90%" onfocusout="blurFunction()" AutoCompleteMode="SuggestAppend" CssCla ...

Can you create asynchronous code or functions without using Web APIs at all?

Even though JavaScript is single-threaded, I can't help but wonder about a function that takes an unusual amount of time without any involvement from web APIs like this: console.log("start") function banana() { let bananaCount = 10; while (b ...

Error Encountered: Module 'openpgp' Not Found

Currently, I am in the process of learning javascript and experimenting with importing modules using npm in my js files. So far, I have been able to successfully import modules using require(), however, I encountered a problem with openpgp.js which resulte ...

What is the best way to merge multiple arrays that have matching keys into one array?

Seeking assistance with PHP as I am a novice in this area. I have an array that looks like: Array ( [_] => Array ( [0] => [1] => ) [123_] => Array ( [0] => 123 [1] => ) [1234_] => Array ( [0] => 1234 [1] => ) ...

Learn the method for automatically checking a checkbox when a page is loaded in Angular

I have multiple checkboxes on a single page <div class="check-outer"> <label>Place of operation</label> <div class="checkDiv"> <div ng-repeat="place in places"> <div class="checkbox-wrapper"> ...

RXJS - distinguishing between values based on multiple keys

I am looking to trigger .subscribe() for my observable when any one of three object keys has been changed. The method works if I manually duplicate it for each key: this.myService.loadData(this.dataContainer.id, true) .distinctUntilChanged((updated ...

Is Node.js truly a single-threaded and non-blocking platform?

As I delve into the world of Node.js, one thing that has caught my attention is the fact that it operates on a single thread and is non-blocking in nature. While I have a solid understanding of JavaScript and how callbacks work, the concept of Node.js bei ...

Laravel and x-editable team up to combat integrity constraint violation error code 1048, indicating no data being passed

Utilizing x-editable to generate an editable form that makes ajax requests. The form is structured as follows: <a href="#" class="editable editable-click" id="mileage" data-name="mileage" data-ty ...

Only one instance of the Next.js inline script is loaded

Incorporating Tiny Slider into my Next.js application has been a success, but I am facing an issue with the inline script that controls the slider's behavior. The script loads correctly when I first launch index.js. However, if I navigate to another p ...

Accessing Data from the Wikipedia API

After receiving a JSON response with the following structure: { "batchcomplete": "", "query": { "pages": { "97646": { "pageid": 97646, "ns": 0, "title": "Die Hard", "extract": "Die Hard is a 1988 ...

Example showcasing callbacks in the Node.js In Action book

I am currently studying the second edition of Node.js in action. I encountered a callback example on page 30 where JSON is displayed in HTML. However, the code I have written below is not functioning as expected and I am unsure of the reason. Despite run ...