Home > Enterprise >  Use reduce method in dart to group consecutive elements in the list like in Javascript
Use reduce method in dart to group consecutive elements in the list like in Javascript

Time:06-30

I have following codes in javascript

var ArrayLogs = [1, 3, 5, 4, 9, 11, 0, -4, -10];
var newLogArrays = [];
 ArrayLogs.reduce(function(result, value, index, array) {
              if (index % 2 === 0){
                newLogArrays.push(array.slice(index, index   2));
              }
              return newLogArrays;
            }, []);

Above method outputs: [[1,3],[5,4],[9,11],[0,-4],[-10]]

I am looking equivalent code in Dart, I know there is reduce method in dart as well, but I am not sure how to use to get similar result as javascript.

Any help will be highly appreciated.

Thanks

CodePudding user response:

If you just want to do it using Dart only, you can do something like the following:

void main() {
  final arrayLogs = [1, 3, 5, 4, 9, 11, 0, -4, -10];

  final result = arrayLogs.fold<List<List<int>>>([], (list, element) {
    if (list.isEmpty || list.last.length > 1) {
      return list..add([element]);
    } else {
      return list..last.add(element);
    }
  });

  print(result);
  // [[1, 3], [5, 4], [9, 11], [0, -4], [-10]]
}

I am sure there are some packages which can do this more automatically or cleaner.

  •  Tags:  
  • dart
  • Related