Sorting a list based on user-defined criteria in Ionic 3

Currently working on a project using Ionic and Firebase, I am faced with the task of comparing arrays produced by users with those stored in Firebase. This comparison is essential for filtering a list of products.

The user can reorder a list containing 3 items (A, B, and C). The order set by the user should then be used to filter another list of products that possess the characteristics A, B, and C. These products are assigned scores and need to be sorted in descending order based on the user's specified sequence.

To achieve this, I must match the user's sorting and only display products that align with their specific order. For example, if the user organizes items as B, A, C, only products sorted in the same way will be shown in the results. This means a product with values A = 50, B = 100, and C = 30 would have an array defined as desOrder = [B, A, C].

An example structure for data stored in Firebase may resemble the following:

- XMnL8KVlJXXXXXXXXXX
    name: "Product 1"
    - desOrder
        0: "B"
        1: "A"
        2: "C"
- XMnX2KVlJXXXXXXXXXX
    name: "Product 2"
    - desOrder
        0: "C"
        1: "B"
        2: "A"
- XnP33RRmNXXXXXXXXXX
    name: "Product 3"
    - desOrder
        0: "A"
        1: "C"
        2: "B"

Within the HTML file 'search.html', you can find the code snippet below:

<ion-list no-lines>
  <ion-item-group class="reordenar" reorder="true" (ionItemReorder)="reorderItem($event)">
    <ion-item *ngFor="let item of orderItems">
      {{ item }}
    </ion-item>
  </ion-item-group> 
</ion-list>

In the corresponding TypeScript file 'search.ts' section, we have the following code:

orderItems: any;

constructor(public navCtrl: NavController, public navParams: NavParams) {
   this.orderItems = ["A", "B", "C"];
}

reorderItem(indexes){
   this.orderItems = reorderArray(this.orderItems, indexes);
   console.log(this.orderItems); // e.g., could be ["B", "C", "A"]
}

searchTo(){
   this.navCtrl.push(ListPage, {this.orderItems}); 
}

At the moment, all products are being displayed without any form of filtering. See 'list.ts' code snippet below:

products: any;

constructor(public navCtrl: NavController, public navParams: NavParams, public listservice: ListService) {
this.getaData();
}

getData(){
  this.products = this.listservice.getAll();
}

'list-service.ts' contains the following logic related to fetching all product data:

getAll(){
  return this.db.list('product/').snapshotChanges()
  .map(changes =>{
    return changes.map(c=> {
      const data = c.payload.val();
      const id = c.payload.key;
      return { id, ...data };;
    });
  })
}

The main focus lies in maintaining the correct ordering, as each product has the same three characteristics and associated scores (distinct from the discussion on this question).

Answer №1

To streamline the process of filtering items based on order, you can assign a unique property to each item indicating its specific order. For instance, in the context of your example: ["B", "C", "A"], you could introduce a property like "itemOrder": "BCA".

By implementing this approach, you can easily filter items using a query like:

ref.orderByChild("itemOrder").equalTo("BCA")
.

If the existing desOrder property already serves a similar purpose, it might be beneficial to convert it from an array to a string format for better efficiency.

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

PHP is encountering issues when attempting to dynamically add rows using JavaScript

I have created this HTML code to dynamically generate rows: <tr > <td><?php echo $row['qty'];?></td> <td class="record"><?php echo $row['prod_name'];?></td> <td><input type ...

Is there a way to make my for loop search for the specific element id that I have clicked on?

When trying to display specific information from just one array, I'm facing an issue where the for loop is also iterating through other arrays and displaying their names. Is there a way to only show data from the intended array? const link = document. ...

What is the best way to retrieve dates from a MySQL database using ExpressJS?

My current task involves retrieving the date value from a MySQL server, but upon printing the result, I encounter an error. In my code, I am able to fetch the date value, however, when attempting to print it, there seems to be an issue with the output. (F ...

Ways to access and delete the canvas using ref steps?

Having a canvas in a react component, I utilized react refs to access the node and implemented a destroy() method. However, I encountered an error: TypeError: canvasRef.current.destroy is not a function How can we properly access the node (canvas) using r ...

Transform this simple XML structure into a PHP array with two dimensions

Presented below is an XML document: <?xml version="1.0" encoding="UTF-8"?> <messages> <message> <from>Person 1</from> <to>Person 2</to> <platform>Instagram Direct Messaging</platform> ...

Exploring Node.js Express: Understanding the Difference Between Modules and Middleware

I am working on an express rest api and need to create a PDF document with a link to download it. I have successfully generated the PDF, but now I want to create a route specifically for returning the PDF link. In addition, I also need other routes that ...

Django Website Experiencing Issues with Google Analytics Integration

I implemented google analytics by inserting the tracking script tag and code at the bottom of the head section in my base.html template which serves as the foundation for all other pages. Additionally, I set up 2 click events to track when users click on ...

When forcibly closing a window, the disconnect event for Socket.IO sockets may not trigger as expected

Currently in the process of creating chat rooms with Socket.io. I've had good success so far, as it's user-friendly and well-documented. However, I've noticed that if I reload the page, wait for the socket to connect, and then close the w ...

Encountering errors with passport-google-oauth20: InternalOAuthError arises when fetching user profile fails and attempting to set headers after they have already been sent to the client

When using passport strategies for various social media logins, I encountered the following two errors: InternalOAuthError: Failed to fetch user profile Cannot set headers after they are sent to the client I suspect that I may have returned a callback or ...

I am currently focusing on using websockets in combination with JavaScript and Golang servers to efficiently transmit files and

When front-end JavaScript websockets send a JSON object, it looks something like this: message_type: "1" to: "umesh" from: "moin" body: "" file: "{"filename":"reportesmtp.pdf" ,"fileextension":"application/pdf" ,"filesize":61813 ,"filedata ...

Launching a new window and displaying content across 2 separate tabs

Currently, I am incorporating both angular js and javascript within my application. An issue that has arisen is that when I click on the <a> tag, it triggers a method in an angular controller which contains $window.open();. The problem lies in the fa ...

Obtain a collection of data- attribute values using jQuery

I am attempting to extract all the values from the data-hiringurl attributes found on this particular page . When I used var data = $("li").attr('data-hiringurl'); and var data = $("li").data('hiringurl'); in the console, an error mess ...

Tips for incorporating ajax to load a new webpage into a specific div container

I have a website with two pages. I want to load Page 2 into a div on Page 1 and then display Page 2 when clicked on. I'm attempting to implement the following code, but it doesn't seem to be working for me. As a beginner, I apologize if this is a ...

Oops! There seems to be a problem with the Node.js App. The MongooseError is indicating that the parameter `uri` in the `openUri()` function should be a string,

I've encountered an issue with my Next.js app involving MongoDB that I've been struggling to resolve. Hoping someone here can provide some insight and help me out. This is quite crucial for my project. First, I'll share the code from my serv ...

I'm struggling to make this script replace the values within the table

I am struggling with a script that I want to use for replacing values in a google doc template with data from a google sheet. The script is able to recognize the variables and generate unique file names based on the information from the google sheet. Howev ...

Performing a double running of an Express GET request with an :id parameter

I'm working on an API using node and express, where the main aim is to capture the :id parameter from the request and store it in a variable. This will allow me to query a specific table in my SQLite database based on that particular id. However, I am ...

A guide to implementing drag and drop functionality using JavaScript

I have developed a unique drag and drop application that features both a left and right panel. The issue I am facing is that when I drag the ball from the left panel to the right panel, it does get dragged successfully. However, the problem arises when the ...

Does the modularization of code impact the performance of the react-app?

The client provided me with a React app that includes an index.jsx file where 90% of the coding has been completed. To prevent getting stuck in Scroll Limbo, I have started breaking down the code into modules for each specific requirement. These include ...

Creating a seamless thread using AngularJS

I am working on a Spring MVC application that utilizes HTML and Angular on the client side. I have a method in my Angular controller that needs to run every 5 seconds. How can I achieve this using Angular? Thank you for your assistance. $scope.inspectio ...

The NodeJS application experiences a crash if incorrect parameters are provided to the API

Currently, I have built a CRUD API using TypeScript with Node.js, Express, and MongoDB. My goal is to ensure that the API functions correctly when the correct parameters are sent through a POST request. However, if incorrect parameters are passed, the Node ...