Utilizing various filters and sorting options on API response within Angular 8

Upon receiving the following API response:

[
    {
      "imgPaths":[
         "gallery/products/55ccb60cddb4d9bded02accb26827ce4"
      ],
      "_id":"5f3e961d65c6d591ba04f3d3",
      "productName":" Jiva Ayurveda Honey (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Jiva",
      "basePrice":"190",
      "finalPrice":"187",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:21.092Z"
   },
   {
      "imgPaths":[
         "gallery/products/72b0e1cf078f26ed0ec0280c1cf8865d"
      ],
      "_id":"5f3e962465c6d591ba04f3d4",
      "productName":"Baidyanath Keshrikalp Royal Chyawanprash (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Baidyanath",
      "basePrice":"394",
      "finalPrice":"378",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:28.103Z"
   }
]

I am looking to implement multiple filters for 'manufacturer' and 'finalPrice', as well as various sorting options such as 'high to low', 'low to high', and 'recently added'. To achieve this, I have written the following methods:

  1. To handle sorting:
    onSortChange(event) {
        if(event.value==="Lowtohigh"){
          this.productsbycategory.sort((a, b) => {
                return Number(a.finalPrice) - Number(b.finalPrice); 
           })
          }
          else if(event.value==="hightolow"){
            this.productsbycategory.sort((a, b) => {
              return Number(b.finalPrice) - Number(a.finalPrice);
            })
           }
          else if(event.value==="recentlyadded"){
            this.productsbycategory.sort((a, b) => {
              return +new Date(b.createdAt) - +new Date(a .createdAt);
            })
        }
    }
  1. For filtering by manufacturer:

onBrandFilterChange(event) {

  if(event.target.checked===true && !numbers.includes(event.target.value)){
    numbers.push(event.target.value);
    this.productsbycategory= _.filter(this.filteredProducts, function(p){
      return _.includes(numbers, p.manufacturer);
    });
  }
  else if(event.target.checked===false && numbers.includes(event.target.value)){
    _.pull(numbers,event.target.value);
    if(numbers.length>0){
    this.productsbycategory= _.filter(this.filteredProducts, function(p){
      return _.includes(numbers, p.manufacturer);
    });
    }
    else{
        this.setData();
    }
  }
}
  1. For filtering by price range:
onPriceFilterChange(min, max) {
    console.log(min, max);
    if (min >= 1 && max <= 5000) {
      this.productsbycategory = this.productsbycategory.filter(function (elem) {
        return Number(elem.finalPrice) >= min && Number(elem.finalPrice) <= max;
      });
    } else {
      alert('Please select a valid price range');
    }
  }


I aim to enhance the existing code to enable applying all filters and sorting functionalities simultaneously. }

Answer â„–1

Make sure to follow this method. Take note of the comments in the code and test it by clicking on the 'Run code snippet' button

// Information you are working with
data = [
    {
      "imgPaths":[
         "gallery/products/55ccb60cddb4d9bded02accb26827ce4"
      ],
      "_id":"5f3e961d65c6d591ba04f3d3",
      "productName":" Jiva Ayurveda Honey (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Jiva",
      "basePrice":"190",
      "finalPrice":"187",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:21.092Z"
   },
   {
      "imgPaths":[
         "gallery/products/72b0e1cf078f26ed0ec0280c1cf8865d"
      ],
      "_id":"5f3e962465c6d591ba04f3d4",
      "productName":"Baidyanath Keshrikalp Royal Chyawanprash (500g) ",
      "categoryId":{
         "_id":"5f2139322d46a455487b2ea6",
         "categoryName":"Nutrition and supplements",
         "imgPath":"gallery/category/c20ae1717899fad2a6ff3f3ceab381ff"
      },
      "manufacturer":"Baidyanath",
      "basePrice":"394",
      "finalPrice":"378",
      "availability":"in-stock",
      "createdAt":"2020-08-20T15:26:28.103Z"
   }
];

// Function for filtering by price
// Input data array, minimum and maximum price
const priceFilter = (data, min, max) => data.filter((item) => item.finalPrice >= min && item.finalPrice <= max);

// Function for filtering by manufacturer
// Provide name
const manFilter = (data, man) => data.filter((item) => item.manufacturer.toLowerCase() === man.toLowerCase());

// Sort the data array based on specific parameters
// Provide data array and options object:
// desc:true for descending sort (ascending as default), 
// price:true to sort by price or date:true to sort by date.
const customSort = (data, { desc, price, date }) => data.sort((a, b) => {
  if(desc) { const c = a; a = b; b = c; }
  if(price) return a.finalPrice - b.finalPrice;
  else if(date) return new Date(a.createdAt) - new Date(b.createdAt);
});

// Testing

// Sort in descending order by date
console.log('Sorting test: ', customSort(data, { desc: true, date: true }));

// Filter by price
console.log('Filtering by price test:', priceFilter(data, 200, 400));

// Filter by name (case insensitive)
console.log('Filtering by name test: ', manFilter(data, 'JIVA'));

If you need to apply multiple filters step by step, follow these steps

// data = [ ... Add your data here... ];

// Start by filtering your data by manufacturer
data = manFilter(data, 'Baidyanath');

// Next, take the previously filtered data
// and filter again by price range
data = priceFilter(data, 100, 300);

// Then, take the data filtered by manufacturer and price range
// and perform an ascending sort based on the price field
data = customSort(data, { price: true });

// Your data is now filtered and sorted
// Proceed with your programming logic
return data;

Answer â„–2

If you need to customize your data filtering:

For the most recently added items:

data.filter(item=>new Date(item.createdAt)).reverse()

To sort from Low to High or High to Low:

data.filter(item=>Number(item.finalPrice)).sort()
data.filter(item=>Number(item.finalPrice)).reverse()

Thank you!

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

Selecting a particular item in a list depending on time using JavaScript, jQuery, or Angular

When working with a JSON file and binding it to list items, I have included a name/value pair in the json for each line indicating audio time, such as "time like 0, 5, 10 in seconds form". In my Cordova application, I am using a media plugin and implement ...

Assign a title property in Vuejs only if the returned data from binding evaluates to true

Just starting out with vuejs and I have a question. How can I set the title based on a value returned from a specific method only if this value is true? Below is my code snippet: <td v-bind="value = getName(id)" :title="value.age" > {{value.na ...

What methods can I utilize to showcase the JSON data on my webpage efficiently?

I'm currently working on a script that makes an ajax request. The Cloud appears to be responding with JSON data, but I'm not sure how to display this data on my webpage. Any suggestions? Here you can find a link to view the neatly formatted JSON ...

Modify the background color of a particular TD element when clicking a button using JavaScript and AJAX

When I click on the "Active account" button inside the designated td with the <tr id="tr_color" >, I want the value "1" to be added to the 'active_account' column in the database. I have been successful with this functionality. However, I a ...

Ensuring the accuracy of nested objects through class validator in combination with nestjs

I'm currently facing an issue with validating nested objects using class-validator and NestJS. I attempted to follow this thread, where I utilized the @Type decorator from class-transform but unfortunately, it did not work as expected. Here is my setu ...

Reusing Angular components multiple times within a single template - dynamically adding lists within them

I created this new component that includes a table (which is an array of key-value pairs) and a form below it. The form is designed to add new values to the table. Here is the Angular code I used: @Component({ selector: 'app-key-value-table', ...

Troubleshooting the error message "TypeError: Cannot read property 'name' of undefined" when working with data binding in Angular 4

I am brand new to Angular and I have been working on creating a custom Component. Specifically, I am trying to display a list of Courses (objects) which consist of two properties: id and name. So far, this logic is functioning properly. However, when attem ...

Repairing the toggle feature using a pair of buttons

I am looking to make changes to my code so that when a button is clicked twice, it reverts back to its original state. Additionally, is there a way to have neither gender button selected upon page load? If you want to see the code in action, follow this l ...

One class seems to be causing issues with hover functionality while the other works perfectly fine

HTML: <div class="channellist"></div> Through the use of Ajax, I am able to dynamically retrieve channels when the page loads and then append them within the channellist container. Once appended, my HTML structure appears as follows: <div ...

Having trouble with validation messages not displaying correctly in Angular after removing a value. What is the correct approach to fix this issue

I've encountered an issue with Angular validation where it's triggering validation on page load, which is not desired. Additionally, when I enter a value, the validation message disappears, but if I return to the textbox and delete the input, the ...

The Chrome Extension XHR always gets a 403 response except when it is triggered from the file:/// protocol

My current project involves the development of a Chrome Extension that relies on the fixer.io API for accessing currency exchange rates. To test this extension, I typically use a simple HTML page where I embed my JavaScript using <script> tags. When ...

The Videojs controls are unresponsive to clicks

Having a strange issue with videojs. I've been attempting to load videojs in the same way as outlined in the documentation, using a dynamic video tag. videojs(document.getElementById('myVideo'), { "controls": true, "autoplay": false, "prelo ...

Having trouble with your JavaScript regex not functioning properly?

I am currently working with an array of arrays and I need to iterate through it to retrieve each word, excluding any "@", punctuation, and hashtags. However, my regular expression seems to be removing certain words entirely from the array and I can't ...

The multi update feature is only compatible with $ operators when performing bulk find and update operations in node.js, as indicated by the Mongo

Why am I receiving the error message MongoError: multi update only works with $ operators when attempting to update multiple documents using the bulk find and update method. Things I have tried: var bulk = db.collection('users').initialize ...

Access information from Google Sheets through an AJAX GET request

I am facing an issue with my code while trying to retrieve data from a Google spreadsheet that I have already published. I have set the share properties of the spreadsheet to 'anyone can edit' and provided the correct URL, but I am still encounte ...

The script for choosing pages is malfunctioning

I'm having trouble with a script on my website. It works on the index page, but not on other pages. <div id="pages"></div>   <script>      a = location.href;      b = a.split('-');      c = b.length;    ...

Strategies for avoiding unused style tags in React components

Expanding beyond React, I'm unsure if React itself is the culprit of this issue. In a React environment with TypeScript, I utilize CSS imports in component files to have specific stylesheets for each component. I assumed these styles would only be ad ...

Why does the browser keep converting my single quotation marks to double, causing issues with my JSON in the data attribute?

This task should be straightforward, but I seem to be facing a roadblock. I am trying to insert some JSON data into an input's data attribute, but the quotes in the first key are causing issues by prematurely closing the attribute. Here is the code ...

Moving an image between different routes using a query

enter image description here I am currently working on a project where I need to take an image input file from the user and display it in another route. To achieve this, I am using query parameters. Issue: However, despite my efforts, the image is not bei ...

When refreshing a page in Next.js, the loading indicator does not properly turn off

I'm currently working on my portfolio using next.js and I have implemented a 'loading' state to prevent displaying partially loaded gallery images. The 'loading' state should turn off (set to 0) once all the photos are fully loaded ...