如何在角度中删除2个数组之间的重复元素?

时间:2023-02-05 04:41:15

Say I have

说我有

arr1 = ["Tom","Harry","Patrick"]

arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"]

How can I remove the duplicate elements in arrays?

如何删除数组中的重复元素?

I want this output

我想要这个输出

arr2 = ["Miguel","Felipe","Mario"]

9 个解决方案

#1


1  

Use filter combined with includes. Example:

使用过滤器结合包含。例:

let arr1 = ["Tom","Harry","Patrick"]
let arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"]
arr2 = arr2.filter(x=>!arr1.includes(x))
console.log(arr2)

#2


1  

If you have lodash, you can use the difference function directly.

如果你有lodash,你可以直接使用差异功能。

_.difference(arr2, arr1) will give the required output.

_.difference(arr2,arr1)将提供所需的输出。

Edit: JSFiddle URL: https://jsfiddle.net/k3ynjq1m/3/

编辑:JSFiddle网址:https://jsfiddle.net/k3ynjq1m/3/

#3


1  

Using includes() is better because returns true or false, but unfortunately it is not supported by IE, see this. In case you want this working on IE too, you should use indexOf().

使用includes()更好,因为返回true或false,但遗憾的是IE不支持它,请参阅此内容。如果您希望这也适用于IE,您应该使用indexOf()。

var arr1 = ["Tom","Harry","Patrick"]

var arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"]

arr2 = arr2.filter(e=>arr1.indexOf(e)<0)

console.log(arr2)

And filter is better because:

过滤器更好,因为:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

#4


0  

Using regular js, you can use a nested for loop:

使用常规js,您可以使用嵌套for循环:

for (var i in arr2) {
  var duplicate = false;
  for (var i2 in arr1) {
    if (arr2[i] == arr1.[i2]) {
      duplicate = true;
    }
  }
  if (duplicate) {
    arr2.splice(i, 1);
  }
}

#5


0  

I think you should keep a map and add elements to that map.

我认为你应该保留一张地图并向该地图添加元素。

if element exists in map, then that is duplicate else add it to map.

The way you can store your duplicates is storing their value in another list. That is up to you.

存储重复项的方法是将其值存储在另一个列表中。那取决于你。

Once you know your duplicates, duplicate it from the list.

一旦知道了重复项,请从列表中复制它。

This is O(n) complexity, and O(n) space complexity.

这是O(n)复杂度和O(n)空间复杂度。

#6


0  

for(var i = 0 ; i<this.arr1.length; i++) {
    for(var j = 0 ; j<this.arr2.length; j++) {
        if(this.arr1[i] === this.arr2[j]) {
            this.arr1.splice(i, 1);
            this.arr2.splice(j, 1);
                i--;
                j--;
        }
    }
}    
this.arr2 = this.arr1.concat(this.arr2);
console.log(this.arr2)

here's a working code (your exemple): https://stackblitz.com/edit/angular-yzte87

这是一个有效的代码(例如):https://stackblitz.com/edit/angular-yzte87

#7


0  

I think that the best way will be to use filter() array method, iterate through the target array (it's arr2 in this case), and exclude duplicates via !arr1.includes(currentItem). This construction lets you know, does arr1 contain current item of iteration:

我认为最好的方法是使用filter()数组方法,遍历目标数组(在这种情况下是arr2),并通过!arr1.includes(currentItem)排除重复项。这个结构让你知道,arr1是否包含当前的迭代项:

const arr1 = ["Tom","Harry","Patrick"];
const arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"];

const result = arr2.filter(d => !arr1.includes(d));
console.log(result);

#8


0  

So the way I see it there are multiple ways to achieve what you're looking for,

所以我看到的方式有多种方法可以实现您的目标,

  1. Using filter and include like some mentioned above me - It will work but I don't know how efficient that will be as you are using filter to iterate on arr2 and then for each element you iterate on arr1 to see if there's matching case, I don't know how familiar you are with algorithm analysis but it's O(N power 2) which is not very time efficient, means quickly as arr1 or arr2 will grow it will take much longer for your function to run, if you do go with that option please use sort() first so you might save time and be more efficient.
  2. 使用过滤器和包括上面提到的一些我 - 它会工作,但我不知道你将使用过滤器迭代arr2然后为你在arr1迭代的每个元素有效,看看是否有匹配的情况,我不知道你对算法分析有多熟悉,但它的O(N次幂2)并不是非常节省时间,意味着arr1或arr2会越来越快,你的功能运行需要更长的时间,如果你这样做的话该选项请先使用sort(),这样可以节省时间并提高效率。

See Example:

  let namesToRemove = ["Tom", "Harry", "Patrick"].sort()
  let names = ["Miguel", "Harry", "Patrick", "Felipe", "Mario", "Tom"].sort()

  let lastNameToRemove = namesToRemove[namesToRemove.length - 1]

  names = names.filter((name) => {
    if (name[0] > lastNameToRemove[0]) {
      return true
    }

    return !namesToRemove.includes(name)
  })

  console.log(names)

Keep in mind that if you will use for loop and splice() you can just break and it will be even more efficient.

请记住,如果你将使用for循环和splice(),你可以打破它,它会更有效率。

  1. Using Map - You can iterate once on your first array and create a map in JS which is just using an object notation and once on your names array and check if there is a match, you can improve that using sort() and other improvement but the idea is, see below example.
  2. 使用Map - 您可以在第一个数组上迭代一次并在JS中创建一个只使用对象表示法的映射,并在您的名称数组上创建一个映射并检查是否存在匹配,您可以使用sort()和其他改进来改进它这个想法是,见下面的例子。

See Example:

  let namesToRemove = ["Tom", "Harry", "Patrick"]
  let names = ["Miguel", "Harry", "Patrick", "Felipe", "Mario", "Tom"]

  let namesToRemoveMap = {}

  for (name of namesToRemove) {
    namesToRemoveMap[name] = true
  }

  names = names.filter((name) => !namesToRemoveMap[name])

  console.log(names)

Of course either way you choose I would include some more defensive checks, like if the arrays have value in them etc...

当然,无论你选择哪种方式,我都会加入更多的防御性检查,比如数组中是否有价值......

Hope I could explain myself clear, let me know if you need more help or if you have any question.

希望我能解释清楚,如果您需要更多帮助或者您有任何疑问,请告诉我。

#9


0  

So you want to remove elements from an array (if they exist) based from another array. Ok, let see... I have a component that implement a function with a similar logic:

因此,您希望从另一个数组中删除数组中的元素(如果存在)。好的,让我们看看......我有一个实现具有类似逻辑的函数的组件:

let criteriaArr = ["Tom", "Harry", "Patrick"];
let arrToFilter = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"];

let filteredArray = arrToFilter.filter(e => criteriaArr.indexOf(e) < 0);

console.log(filteredArray);

So what filter does is: Returns the elements of an array that meet the condition specified in a callback function.

所以过滤器的作用是:返回满足回调函数中指定条件的数组元素。

what the callback function does is: for each element from arrToFilter, if that element does not exit in criteriaArr then keep it otherwise go to the next element.

回调函数的作用是:对于来自arrToFilter的每个元素,如果该元素没有在criteriaArr中退出,那么保留它,否则转到下一个元素。

Here is the function:

这是功能:

removeElems(arrToFilter: Array<any>): Array<any> {
  let filteredArray = arrToFilter.filter(e => this._criteriaArr.indexOf(e) < 0);
  return filteredArray;
}

this._criteriaArr is a private property with default value: private _criteriaArr = ["Tom","Harry","Patrick"]

this._criteriaArr是一个私有属性,默认值为:private _criteriaArr = [“Tom”,“Harry”,“Patrick”]

Or, you can do it this way:

或者,你可以这样做:

removeElems(arrToFilter: Array<any>, criteriaArr: Array<any>): Array<any> {
  let filteredArray = arrToFilter.filter(e => criteriaArr.indexOf(e) < 0);
  return filteredArray;
}

handle it with two array.

用两个数组处理它。

have fun ! :)

玩的开心 ! :)

#1


1  

Use filter combined with includes. Example:

使用过滤器结合包含。例:

let arr1 = ["Tom","Harry","Patrick"]
let arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"]
arr2 = arr2.filter(x=>!arr1.includes(x))
console.log(arr2)

#2


1  

If you have lodash, you can use the difference function directly.

如果你有lodash,你可以直接使用差异功能。

_.difference(arr2, arr1) will give the required output.

_.difference(arr2,arr1)将提供所需的输出。

Edit: JSFiddle URL: https://jsfiddle.net/k3ynjq1m/3/

编辑:JSFiddle网址:https://jsfiddle.net/k3ynjq1m/3/

#3


1  

Using includes() is better because returns true or false, but unfortunately it is not supported by IE, see this. In case you want this working on IE too, you should use indexOf().

使用includes()更好,因为返回true或false,但遗憾的是IE不支持它,请参阅此内容。如果您希望这也适用于IE,您应该使用indexOf()。

var arr1 = ["Tom","Harry","Patrick"]

var arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"]

arr2 = arr2.filter(e=>arr1.indexOf(e)<0)

console.log(arr2)

And filter is better because:

过滤器更好,因为:

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

filter()方法创建一个新数组,其中包含通过所提供函数实现的测试的所有元素。

#4


0  

Using regular js, you can use a nested for loop:

使用常规js,您可以使用嵌套for循环:

for (var i in arr2) {
  var duplicate = false;
  for (var i2 in arr1) {
    if (arr2[i] == arr1.[i2]) {
      duplicate = true;
    }
  }
  if (duplicate) {
    arr2.splice(i, 1);
  }
}

#5


0  

I think you should keep a map and add elements to that map.

我认为你应该保留一张地图并向该地图添加元素。

if element exists in map, then that is duplicate else add it to map.

The way you can store your duplicates is storing their value in another list. That is up to you.

存储重复项的方法是将其值存储在另一个列表中。那取决于你。

Once you know your duplicates, duplicate it from the list.

一旦知道了重复项,请从列表中复制它。

This is O(n) complexity, and O(n) space complexity.

这是O(n)复杂度和O(n)空间复杂度。

#6


0  

for(var i = 0 ; i<this.arr1.length; i++) {
    for(var j = 0 ; j<this.arr2.length; j++) {
        if(this.arr1[i] === this.arr2[j]) {
            this.arr1.splice(i, 1);
            this.arr2.splice(j, 1);
                i--;
                j--;
        }
    }
}    
this.arr2 = this.arr1.concat(this.arr2);
console.log(this.arr2)

here's a working code (your exemple): https://stackblitz.com/edit/angular-yzte87

这是一个有效的代码(例如):https://stackblitz.com/edit/angular-yzte87

#7


0  

I think that the best way will be to use filter() array method, iterate through the target array (it's arr2 in this case), and exclude duplicates via !arr1.includes(currentItem). This construction lets you know, does arr1 contain current item of iteration:

我认为最好的方法是使用filter()数组方法,遍历目标数组(在这种情况下是arr2),并通过!arr1.includes(currentItem)排除重复项。这个结构让你知道,arr1是否包含当前的迭代项:

const arr1 = ["Tom","Harry","Patrick"];
const arr2 = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"];

const result = arr2.filter(d => !arr1.includes(d));
console.log(result);

#8


0  

So the way I see it there are multiple ways to achieve what you're looking for,

所以我看到的方式有多种方法可以实现您的目标,

  1. Using filter and include like some mentioned above me - It will work but I don't know how efficient that will be as you are using filter to iterate on arr2 and then for each element you iterate on arr1 to see if there's matching case, I don't know how familiar you are with algorithm analysis but it's O(N power 2) which is not very time efficient, means quickly as arr1 or arr2 will grow it will take much longer for your function to run, if you do go with that option please use sort() first so you might save time and be more efficient.
  2. 使用过滤器和包括上面提到的一些我 - 它会工作,但我不知道你将使用过滤器迭代arr2然后为你在arr1迭代的每个元素有效,看看是否有匹配的情况,我不知道你对算法分析有多熟悉,但它的O(N次幂2)并不是非常节省时间,意味着arr1或arr2会越来越快,你的功能运行需要更长的时间,如果你这样做的话该选项请先使用sort(),这样可以节省时间并提高效率。

See Example:

  let namesToRemove = ["Tom", "Harry", "Patrick"].sort()
  let names = ["Miguel", "Harry", "Patrick", "Felipe", "Mario", "Tom"].sort()

  let lastNameToRemove = namesToRemove[namesToRemove.length - 1]

  names = names.filter((name) => {
    if (name[0] > lastNameToRemove[0]) {
      return true
    }

    return !namesToRemove.includes(name)
  })

  console.log(names)

Keep in mind that if you will use for loop and splice() you can just break and it will be even more efficient.

请记住,如果你将使用for循环和splice(),你可以打破它,它会更有效率。

  1. Using Map - You can iterate once on your first array and create a map in JS which is just using an object notation and once on your names array and check if there is a match, you can improve that using sort() and other improvement but the idea is, see below example.
  2. 使用Map - 您可以在第一个数组上迭代一次并在JS中创建一个只使用对象表示法的映射,并在您的名称数组上创建一个映射并检查是否存在匹配,您可以使用sort()和其他改进来改进它这个想法是,见下面的例子。

See Example:

  let namesToRemove = ["Tom", "Harry", "Patrick"]
  let names = ["Miguel", "Harry", "Patrick", "Felipe", "Mario", "Tom"]

  let namesToRemoveMap = {}

  for (name of namesToRemove) {
    namesToRemoveMap[name] = true
  }

  names = names.filter((name) => !namesToRemoveMap[name])

  console.log(names)

Of course either way you choose I would include some more defensive checks, like if the arrays have value in them etc...

当然,无论你选择哪种方式,我都会加入更多的防御性检查,比如数组中是否有价值......

Hope I could explain myself clear, let me know if you need more help or if you have any question.

希望我能解释清楚,如果您需要更多帮助或者您有任何疑问,请告诉我。

#9


0  

So you want to remove elements from an array (if they exist) based from another array. Ok, let see... I have a component that implement a function with a similar logic:

因此,您希望从另一个数组中删除数组中的元素(如果存在)。好的,让我们看看......我有一个实现具有类似逻辑的函数的组件:

let criteriaArr = ["Tom", "Harry", "Patrick"];
let arrToFilter = ["Miguel","Harry","Patrick","Felipe","Mario","Tom"];

let filteredArray = arrToFilter.filter(e => criteriaArr.indexOf(e) < 0);

console.log(filteredArray);

So what filter does is: Returns the elements of an array that meet the condition specified in a callback function.

所以过滤器的作用是:返回满足回调函数中指定条件的数组元素。

what the callback function does is: for each element from arrToFilter, if that element does not exit in criteriaArr then keep it otherwise go to the next element.

回调函数的作用是:对于来自arrToFilter的每个元素,如果该元素没有在criteriaArr中退出,那么保留它,否则转到下一个元素。

Here is the function:

这是功能:

removeElems(arrToFilter: Array<any>): Array<any> {
  let filteredArray = arrToFilter.filter(e => this._criteriaArr.indexOf(e) < 0);
  return filteredArray;
}

this._criteriaArr is a private property with default value: private _criteriaArr = ["Tom","Harry","Patrick"]

this._criteriaArr是一个私有属性,默认值为:private _criteriaArr = [“Tom”,“Harry”,“Patrick”]

Or, you can do it this way:

或者,你可以这样做:

removeElems(arrToFilter: Array<any>, criteriaArr: Array<any>): Array<any> {
  let filteredArray = arrToFilter.filter(e => criteriaArr.indexOf(e) < 0);
  return filteredArray;
}

handle it with two array.

用两个数组处理它。

have fun ! :)

玩的开心 ! :)