简体   繁体   English

组合阵列以消除重复项的最有效方法

[英]Most Efficient way to Combine Arrays removing Duplicates

Using a Flatlist and looking for an efficient way to combine elements of a list, while removing the duplicate elements. 使用“平面列表”并寻找一种有效的方式来组合列表中的元素,同时删除重复的元素。 Each element has a unique key value, to know whether it is a duplicate or not. 每个元素都有一个唯一的键值,以了解它是否重复。

My current implimentation uses the concat function: 我当前的实现使用concat函数:

Array.prototype.unique = function() {
      var a = this.concat();
      for(var i=0; i<a.length; ++i) {
          for(var j=i+1; j<a.length; ++j) {
              if(a[i].key === a[j].key)
                  a.splice(j--, 1);
          }
      }
      return a;
  };

const OldArray = this.state.data;
const NewArray = [] //contains values we loaded in 
const FinalArray = OldArray.concat(NewArray).unique();

//Update the State
this.setState({
   data: FinalArray
)}

This definitely works, but every time this function runs its at least N^2 efficiency, which seems bad. 这肯定有效,但是每次此函数运行其效率至少为N ^ 2时,这似乎很糟糕。 Is there a better way to do this? 有一个更好的方法吗? I feel like there must be.. 我觉得一定有..

You can use Array#reduce to creae a Map of unique values, and then spread it back to an array. 您可以使用Array#reduce创建唯一值的Map,然后将其传播回数组。 This will get you the 1st appearance of the objects that have the same key. 这将使您获得具有相同键的对象的第一外观。

 const union = (arr1, arr2, key) => [... // spread to an array arr1.concat(arr2) // concat the arrays .reduce((m, o) => m.has(o[key]) ? m : m.set(o[key], o), new Map) // reduce to a map by value of key .values()]; // get the values iterator const OldArray = [{ a: 1, v: 1 }, { a: 2 }] const NewArray = [{ a: 1, v: 100 }, { a: 3 }] const FinalArray = union(OldArray, NewArray, 'a') console.log(FinalArray); 

The other option, as suggested by @4castle, is to use Array#map to initialize the Map. @ 4castle建议的另一种选择是使用Array#map初始化Map。 However, this will take the last appearance of the objects that have the same key. 但是,这将采用具有相同键的对象的最后外观。 You can always Array#reverse the array before initializing the Map. 在初始化地图之前,您始终可以Array#reverse数组。

 const union = (arr1, arr2, key) => [... // spread to an array new Map(arr1.concat(arr2).map(o => [o[key], o])) // concat and initialize the map .values()]; // get the values iterator const OldArray = [{ a: 1, v: 1 }, { a: 2 }] const NewArray = [{ a: 1, v: 100 }, { a: 3 }] const FinalArray = union(OldArray, NewArray, 'a') console.log(FinalArray); 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM