OneBite.Dev - Coding blog in a bite size

Sort Items In Array By Desc In Dart

Code snippet for how to Sort Items In Array By Desc In Dart with sample and detail explanation

Sorting items in an array in descending order is a frequently used operation in programming. Here, we are going to explore how to sort an array in descending order in Dart, a language widely used for mobile, web, and desktop applications.

Code snippet for Sorting Items In Array By Desc In Dart

Before we delve into the explanation, let’s look at the code snippet that effectively handles the task.

void main() { 
   var myArr = [45, 78, 32, 56];
   myArr.sort((b, a) => a.compareTo(b));
   print(myArr);
} 

Upon running this piece of code, the array will be printed out as [78, 56, 45, 32], indicating the items of the array have been sorted in the descending order.

Code Explanation for Sorting Items In Array By Desc In Dart

The code for sorting an array in the descending order in Dart is quite simple and straight-forward. Here’s a step by step tutorial on how it works.

The first step is to define the array that you intend to sort. In this case, we have created a variable myArr and set it as [45, 78, 32, 56].

var myArr = [45, 78, 32, 56];

The next step is to sort the numbers in the array in descending order. Dart has a handy sort function, which we’ll use here. The sort function uses a comparator function to determine the order of sort.

myArr.sort((b, a) => a.compareTo(b));

In the comparator function, a and b are two adjacent elements in the array. The compareTo function returns a negative value if a is smaller, a positive value if a is larger, and zero if they’re equal. So, by comparing a to b, we order them in descending order.

Finally, we print out the sorted array.

print(myArr);

When we run the code, Dart sorts the array in descending order and prints the sorted myArr: [78, 56, 45, 32].

And that’s all. Using this code snippet, you can sort items in an array in descending order in Dart with ease and efficiency.

dart