Mapping an array by index

It can be useful while indexing over an iterable to know the "index" of the current item you are handling. Dart's default Iterable.map does not provide a way, by default, of accessing the index while mapping. Below are a few solutions to getting it done.

Raw Dart Solution

The following solution uses no libraries and accomplishes the goal with very little extra code:

raw.dart
final list = [1, 2, 3, 4, 5];

// We start with -1 because we increment as the first operation in the callback below
// If you want to increment as the last operation, then start with 0
var idx = -1;

final result = list.map((el) {
  idx += 1;
  return el * idx; // Do something with the index
});
// result: [0, 2, 6, 12, 20]

Using Quiver Package

Quiver is a set of utility libraries build and maintained by Google for Dart that "makes using many Dart libraries easier and more convenient, or adds additional functionality."

After installing the package, the following code can be used to achieve the same result as above:

using_quiver.dart
import 'package:quiver/iterables.dart';

final list = [1, 2, 3, 4, 5];
final result = enumerate(list).map((el) => el.value * el.index);
// result: [0, 2, 6, 12, 20]

Using list_ext Package

list_ext is a Dart extension for Iterables and Lists that adds functionality as if they were built-in methods.

Full Disclosure: I submitted the PR to add mapIndex to this library.

After installing version 1.0.6 or later of the package, the following code can be used to achieve the same result as above:

using_list_ext.dart
import 'package:list_ext/list_ext.dart';

final list = [1, 2, 3, 4, 5];
final result = list.mapIndex((el, idx) => el * idx);
// result: [0, 2, 6, 12, 20]

Note: mapIndex uses quiver's enumerate behind the scenes.

Credits

This post and code brought to you by the following twitter conversation:

Brian Armstrong

Brian Armstrong

I'm Brian Armstrong, a SaaS developer with 15+ years programming experience. I am a Flutter evangelist and React.js enthusiast.