0
votes
  • I write a function that takes two arrays as a parameter and the function merge the arrays, tried to print the merged list but I have the error Uncaught Error: TypeError: 21: type 'JSInt' is not a subtype of type 'bool' and tried to make the function to return the list and I print it in another function but I still had the same error, i think the error because the function return type but I tried it as void and yes I know void not work because I have if and it return list or List but not working, or because the editor I use the dart bad online
  • there's any suggestion to make the function more efficiant for this problem?
  var list = [];
  var arr1Item = arr1[0];
  var arr2Item = arr2[0];
  var i = 1;
  var j = 1;

  if (arr1.length == 0) {
    return arr2;
  }
  if (arr2.length == 0) {
    return arr1;
  }
  while (arr2Item || arr1Item) {
    if (!arr2Item || arr1Item < arr2Item) {
      list.add(arr1Item);
      arr1Item = arr1[i];
      i++;
    } else {
      list.add(arr2Item);
      arr2Item = arr2[i];
      j++;
    }
  }
  print(list);
}
void main() {
  reverseString([1, 2, 5, 31], [21, 5, 8]);
}
1

1 Answers

0
votes

Unlike in JavaScript, you can't simply check for a truthy value of an array. The code if (arr) will throw an error, because arr doesn't evaluate to a bool value.

I'm not entirely sure what you're trying to achieve here, but some thoughts regarding efficient Dart / Flutter:

To merge two arrays, you can simple add the arrays.


final array1 = [1, 2, 3];
final array2 = [4, 5, 6];

final joinedArray = array1 + array2;
print(joinedArray); // [1, 2, 3, 4, 5, 6];

Instead of checking for length == 0, use isEmpty.

if (arr1.isEmpty)

The reversing of an array can be done using the inbuilt .reversed method.

final reversedArray = array1.reversed;