How to remove item in mutable array?

I want remove some items in a mutable array, But I don’t find the remove or some functions in Array base library.

And I find some examples:

  // Clear to-do item utility
  public func clear(todos: [ToDo]) : [ToDo] {
    var updated : [ToDo] = [];
    for (todo : ToDo in todos.vals()) {
      if (not todo.completed) {
        updated := Array.append<ToDo>(updated, [todo]);
      };
    };
    updated
  };

This is by creating a new array and copying all the elements except to the be deleted one into the new array. is this will result in poor performance for relatively large arrays?

2 Likes

Arrays in Motoko are fixed size as in languages like Java and C# (and unlike Javascript).

If you want to support deletion without full copying, it might be better to choose a different data structure like List (a single-linked list) (see List.filter) or something more fancy like TrieSet.

Even the Array.append method will copy contents into a new array and should therefore be avoided when worried about efficiency (e.g. in inner loops).

Hope that helps!

We should probably rework some of the examples but they were always written for simplicity of presentation, not necessarily efficiency.

6 Likes