如何使数组(列表)元素在 Dart 中独一无二



我需要从列表中删除多余的(字符串)元素。 或者也许首先防止它们被输入是更好的解决方案? 集合不允许重复,但它们也不保持顺序,我需要顺序。 这对我来说是一个常见问题,所以我正在寻找一种可能的语言解决方案,以充分发挥效率。

(过去,我扩展了一个数组类来添加我自己的add_unique()方法,但这似乎是一个足够常见的问题,可以由语言处理,并且可能更有效。

谢谢

_g

数组对象 DART,在 https://dartpad.dev/4d3a724429bbd605f4682b7da253a16e 中测试

void main() {
      var duplicates = [
        {"b": 1},
        {"b": 2},
        {"b": 1},
        {"b": 2}
      ];
    
      var resArr = [];
      duplicates.forEach((item) {
        var i = resArr.indexWhere((x) => x["b"] == item["b"]);
        if (i <= -1) {
          resArr.add({"b": item["b"]});
        }
      });
      print(resArr);
    }

您需要一个 LinkedSet 来仅包含唯一身份并保持广告顺序,但目前我们在 dart 中没有它。但是,您可以使用 LinkedHashMap 模拟 LinkedSet:

var input = ["apple", "orange", "cherries", "pears", "apple", "apple", "orange"];
var uniques = new LinkedHashMap<String, bool>();
for (var s in input) {
  uniques[s] = true;
}
for (var key in uniques.getKeys()) {
  print ("$key");
}

今天,这必须手动完成。Dart 不提供保持广告顺序的套装。请注意,Dart 容器库将进行改造。请访问 www.dartbug.com 并添加此功能请求。要手动执行此操作,您可以:

1) 在添加之前调用索引。2)维护一个集合和一个列表。集合可用于保持事物的唯一性,而列表则保持秩序。

我会推荐1。

John

您可以像以前一样使用该列表,并按照cutch提到的手动添加自己的方法来验证重复项和排序,如下所示。

import 'dart:html';
var someList = new List<String>();
String newItem = '';
void main() {
  newItem = 'item 3';  
  if(!itemExistsInList(someList, newItem)){
    someList.add(newItem);
    sortList(someList);
  }
  // expected item 3
  print(someList);
  newItem = 'item 1';
  if(!itemExistsInList(someList, newItem)){
    someList.add(newItem);
    sortList(someList);
  }
// expected item 1, item 3
  print(someList);
  newItem = 'item 3';
  if(!itemExistsInList(someList, newItem)){
    someList.add(newItem);
    sortList(someList);
  }
// expected item 1, item 3. Same as previous as secondary item 3 was not added
  print(someList);
}
// returns true if the specified item already exists in the specified list
// otherwise false
bool itemExistsInList(List<String> list, String item){
  return list.some((v) => v.indexOf(item) != -1);
}
// sorts the list
void sortList(List<String> list){
  list.sort((a, b) => a.compareTo(b));
}

您不需要每次添加时都调用 sortList() 函数,我这样做只是为了演示。只有在您实际需要时才调用它就足够了。

.sort().some().indexOfDART库文档的集合部分有更详细的解释。

最新更新