Click on the button to sort Angular data

Greetings! I am a newcomer trying to grasp the concepts of angularjs/typescript.

I have compiled an array of fruits, displayed in an unordered list. My goal is to arrange them in descending order and implement a reverse search function to display the items in alphabetic order upon clicking a button. However, I am unsure of how the function should be implemented... Any assistance would be greatly appreciated!

Here is the snippet of HTML code:

export class AppComponent {
  fruits: string[] = ["Apple", "Banana", "Orange", "Peach", "Pear"];
}
<ul>
  <li *ngFor="let fruits of fruits">{{fruits}}
  </li>
</ul>

<button ng-click="send()">Sort </button>

Answer №1

Where are all the fruits hiding?

By the way:

export class AppComponent {
  cities: string[] = [ "Pear","Banana", "Apple", "Orange", "Peach" ];
}

Alright, now let's display them:

  <ul>
      <li *ngFor="let city of cities">{{city}}
      </li>
    </ul>

    <button (click)="send()">Sort </button>

And here is the sorting function to use:

send(){
    this.cities = this.cities.sort(); 
}

Answer №2

One way to achieve this is by utilizing the sort() function.

 sortFruits(){
    this.fruits = this.fruits.sort((n1,n2) => {
    if (n1 < n2) {
        return 1;
    }

    if (n1 > n2) {
        return -1;
    }

    return 0;
});
  }

You can view your solution here on stackBlitz.

Answer №3

Revise the sort() method to arrange strings in alphabetical order.

 send(){
     this.fruits.sort((n1,n2) => {
  return n1.localeCompare(n2)  
});

For a demonstration, refer to the example on StackBlitz: stackblitz link

To switch between sorting orders, define a variable, check its value, and sort accordingly.

send(){
    this.order = !this.order;
     this.fruits.sort((n1,n2) => {       
      return (this.order)? n1.localeCompare(n2):n2.localeCompare(n1);
    });
  }

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

Manipulate the visibility of div sections depending on the selected price and category checkboxes using JavaScript

I have a unique div setup where I'm defining data attributes to display a product list. Each div contains data attributes for category (data-category) and price (data-price). I want to be able to show or hide specific divs based on selections made usi ...

Managing errors that occur while handling JSON with AJAX by implementing a suitable backup plan

Imagine there is a user.json file stored on a web server that contains: { "name” : “ivana”, “age” : “27” } Now, I make a request to retrieve this JSON data using the following code: var user = $.ajax({ url: pathsample.com/user.js ...

Utilizing the import feature for structuring the routes folder in Express with Node.js

Recently, I made the switch to using ECMAScript (ES6) for my NodeJS Rest API with Express, and I've encountered a few challenges when working with the new keyword import In the past, I would organize my routes folder like this: Let's imagine th ...

Can Python's datetime object be used interchangeably with a JavaScript date object?

Take for instance in python, a date might look like: 2020-06-19T11:32:16.548109Z, is there a method I can utilize to transform this into a javascript Date object? ...

AngularJS personalized date selector directive

Looking to create a unique datepicker directive with a personalized template. Feeling lost on where to begin constructing it... Any suggestions on incorporating date data into my directive? Your guidance or tips on how to approach this project more effe ...

Exploring the capabilities of CasperJS through double clicking

I'm currently working on creating a bot using CasperJS. The main goal is for the bot to send trade offers by offering an item, but I'm facing difficulties in figuring out how to click on the item. I attempted to use Resurrectio, however, it' ...

What is the procedure for placing an item into a vacant area in react-dnd?

Looking to create a drag and drop list using react-dnd. Manage to put together an example: visit codesandbox example here Currently facing one issue: Unable to drop an item into an empty section. If trying to move image1 to the first or third group, un ...

Executing a Function Prior to onClick Event of a Link Element in Next.js

While working on a slider/carousel, I encountered an issue. Each photo in the slider should be draggable back and forth, with a click taking the user to a product page. I am using next.js with react-flickity-component for this purpose. Please note that thi ...

The Component TSX is reporting a Type error stating that the Property 'onChange' is not present in the type '{ key: string; value: Model; }' as required by Props

While running the following command: npm run build I encountered an error that needs resolution: /components/Lane.tsx:37:18 Type error: Property 'onChange' is missing in type '{ key: string; value: StepModel; }' but required in type &a ...

Is the Ngx-bootstrap popover automatic positioning malfunctioning when placed on the right side of the screen?

I am currently facing an issue while implementing popovers on our application using Angular 6.0.1, Ngx-bootstrap 2.0.5, and Bootstrap 4.1.1. The problem arises when I use 'auto' positioning for the popovers, specifically on the right side of the ...

Error message: When working with Protobuf, an uncaught reference error occurs because the 'exports

Currently, I am in the process of configuring protobuf to work with typescript. According to the official Google Documentation, all that is needed is to execute npm install google-protobuf and then to include require('google-protobuf'). Unfortu ...

SheetJS is experiencing difficulties parsing dates correctly

Need help exporting an HTML table to an Excel file using the SheetJS library. Here's my code snippet: var table = document.getElementById("tableToExport"); var ws = XLSX.utils.table_to_sheet(table, { sheet: "Raport Odorizare", da ...

Utilize a singular loader when simultaneously making numerous HTTP requests in Angular with ngx-ui-loader

After successfully implementing the ngx-ui-loader and setting the NgxUiLoaderHttpModule for all HTTP requests in my project, everything is working fine. However, I have encountered an issue on certain routes where multiple HTTP requests are being executed ...

Save the entire compiler output as a text or CSV file by using the "strict":true compiler option in TypeScript

The tsconfig.json file in my Visual Studio project includes the following settings: { "CompileOnSave":false, "CompilerOptions":{ "strict": true, "skipLibCheck":true }, "angularCompilerOptions":{ "fullT ...

Having trouble setting up a successful connection with Socket.io client?

I'm struggling to integrate websockets into my website. Every attempt I make in the client results in errors. This is how I have Apache configured: <VirtualHost *:80> ServerName xxxxx.com DocumentRoot /var/www/html/RoW ErrorLog /var/www/html/Ro ...

Adjust the color of text as you scroll

Could you provide guidance on changing the color of fixed texts in specific sections of my portfolio website? Unfortunately, I can't share my lengthy code here, but would greatly appreciate it if you could illustrate with examples. Here's a refer ...

Exploring how to access properties of objects in javascript

As a novice on this platform, I'm uncertain if the title may be deceiving, but I have a question regarding the following scenario: var someObject ={} someObject.info= { name: "value" }; How can I acce ...

The error thrown states: "TypeError: Unable to access the property 'getFieldDecorator' of undefined in a React component."

Encountering this error: > TypeError: Cannot read property 'getFieldDecorator' of undefined > _class.render src/containers/RegisterTenant/register.js:81 78 | this.setState({ 'selectedFiles': files }); 79 | } 80 | > ...

Ways to set a default value for a union type parameter without encountering the error "could be instantiated with a different subtype of constraint"

After referring to my recent inquiry... Can a default value be specified for valueProp in this scenario? type ValueType = 'value' | 'defaultValue' type Props<T extends ValueType> = Record<T, string> ...

The CORS Policy has prevented Angular from accessing the header, as the request header field for authentication is restricted

After reviewing a multitude of similar questions regarding CORS and headers, I have attempted various solutions but I am still encountering this error specifically in Google Chrome. Access to XMLHttpRequest at 'https://service.domain.com/clientlist&ap ...