JavaScript: removing duplicates in an array of arrays

JavaScript is currently in use, and I need to go through an array of arrays to determine if there are duplicate arrays, and then delete those duplicated arrays. Runtime is an entity in this case, so I was wondering what is the most efficient way to do this.

Is a hash table used in this case? The scope of this will be the hash sequence of each sequence, and then use the hash to determine the repetition of this sequence. Therefore, each sequence is an array inside the main array, and any duplicates will be other arrays inside the same array. In addition, it is extremely important that all individual arrays remain ordered (i.e., Elements in separate arrays must always maintain their position). In addition, all elements in a separate array are string values.

Example. Suppose that there exists an array A , whose elements in turn are the following arrays:

A[0] = ["one", "two", "three", "four"]
A[1] = ["two", "one", "three", "four"]
A[2] = ["one", "two", "three", "four"]

In the above example, A [0] and A [2] are duplicates, so the function should return A [0] and A [1], so that there is only one instance of the same array.

+4
source share
2 answers

Store the object where the keys are the combined elements of each array. If the key is not found, add the array to the output array and add the key to the object.

var hash = {};
var out = [];
for (var i = 0, l = A.length; i < l; i++) {
  var key = A[i].join('|');
  if (!hash[key]) {
    out.push(A[i]);
    hash[key] = 'found';
  }
}

Demo

+6
source

, : n , k , O(n^2 * k) , n n-1 k . O(n*k)

, , : ( : , k , , .)

, , a. -, , . , a , a node. , node . , b, b a.

: ( : )

a - b

c, :

a - b - c

, [a, c, d]. a. , c . , :

  - b - c
a
  - c

:

  - b - c
a
  - c - d

, , , : [a, b, c]

a, , -. , a b, b. , , , , , , .

, , . , . , O(n*k). , O(n*k), , .

, .

+1

All Articles