Lists or Arrays

1. map()

The map() method creates a new list that contains the results of running a callback on every element in the original list.

var cars = [ 'mercedes’,‘bmw’,‘audi’,'tesla'];

var mapCars = cars.map((car) => ‘My car is $car’).toList();

print(mapCars);

The output of the above code would be:

[My car is mercedes, My car is bmw, My car is audi, My car is tesla]

2. sort()

sort() can be used to order the elements based on the provided sorting function. It works without a function too.

cars.sort();

print(cars); or using method cascades print(cars..sort());

The above snippets will print this:

[audi, bmw, mercedes, tesla]

We can always define our own comparison logic as well. Say we need to sort by comparing the price of each car, which will be obtained from a function getPrice() . We write our sort logic, as shown below, and it will sort the cars list based on their given price:

cars .sort((a, b) => getPrice(a).compareTo(getPrice(b)));

3. contains()

This is used to check if a given element is present in a list. contains() returns a boolean value.

print(cars.contains('bmw')); // output => true

print(cars.contains('toyota')); // output => false

4. reduce()

This method also runs a callback for each element of an array. But reduce passes the result of each callback to the next iteration. This passed value is commonly known as an accumulator (value is accumulated through each iteration).

var numbers = [1, 3, 2, 5, 4];

var product = numbers.reduce((curr, next) => curr * next);

print(product);

The output of the above snippet will be 120 .

Which is obtained from: 1*3 + 3*2 + 6*5 + 30*4.

Here accumulators after each iteration would be 3, 6, 30, and 120 respectively.