使用Javascript - 快速删除对象数组复制数组、对象、快速、Javascript

2023-09-11 05:04:25 作者:轉身流淚っ

我有2个阵列,在他们的对象,如:

I have 2 arrays with objects in them such as:

[{"Start": 1, "End": 2}, {"Start": 4, "End": 9}, {"Start": 12, "End": 16}, ... ]

我想在删除重复合并2个数组。目前,我做了以下内容:

I want to merge the 2 arrays while removing duplicates. Currently, I am doing the following:

array1.concat(array2);

然后我做了嵌套的 $。每个循环,但我的阵列变得越来越大,这需要为O(n ^ 2) 的时间来执行,而不是可扩展性。

Then I am doing a nested $.each loop, but as my arrays get larger and larger, this takes O(n^2) time to execute and is not scalable.

我presume有一种更快的方式做到这一点,但是,所有的我发现正在使用字符串或整数的例子。

I presume there is a quicker way to do this, however, all of the examples I have found are working with strings or integers.

任何推荐的算法或方法在那里使这个更快?

Any recommended algorithms or methods out there to make this faster?

推荐答案

这个假设答案碱基顺序并不重要,你可以从你的对象创建唯一的密钥。

This answer bases on the assumption that the order does not matter and you can create unique keys from your objects.

您复制所有n个条目,从一个对象C的阵列,创造一个独特的关键,在这之后,你从数组b复制所有m组到该对象(这将自动消除重复的),你的 O(N + M):

You copy all n entries from the array a to an object c, creating a unique key, after that you copy all m entries from array b to that object (this will automatically eliminate the duplicates) and you are finished in O(n+m):

var a = [{"Start": 1, "End": 2}, {"Start": 4, "End": 9}];
var b = [{"Start": 4, "End": 9}, {"Start": 3, "End": 12}];

var c = {};
a.forEach(function(el){c[el.Start+".."+el.End] = el});
b.forEach(function(el){c[el.Start+".."+el.End] = el});

console.log(c);
// yields: {"1..2":{"Start": 1, "End": 2},"4..9":{"Start": 4, "End": 9},"3..12":{"Start": 3, "End": 12}}

这个符号在这个对象是有点多余,但你是在合并两个数组非常快。也许这可进一步改进。

This notation in this object is a bit redundant but you are extremely fast on merging the two arrays. Maybe this could be improved further.