简体   繁体   English

比较 javascript 中两个 Arrays 的元素

[英]Comparing Elements of two Arrays in javascript

I have 2 arrays like below我有 2 个 arrays 如下所示

var array1=["m","m","r","r"];
var array2=["r","r","m","r"];

and I want to compare both the arrays.我想比较 arrays。

If the first element of array1 (which is "m" ) is present in array2 then remove both the elements from both the array.如果array1的第一个元素(即"m" )存在于array2中,则从两个数组中删除这两个元素。 then arrays should become as below那么 arrays 应该变成如下

array1=["m","r","r"];
array2=["r","r","r"];

Again it is required to check if the first element from updated array1 (which is "m" ) is present in updated array2 then remove both the elements from both the array.再次需要检查更新后的array1中的第一个元素(即"m" )是否存在于更新后的array2中,然后从两个数组中删除这两个元素。 However, if the first element from updated array1 is not present in updated array2 then break the statement.但是,如果更新后的array1中的第一个元素不在更新后的array2中,则中断该语句。

There are few ways to achieve this, you could either do two loops or use a more effective solution with better time complexity using a hash-map.实现这一点的方法很少,您可以执行两个循环,或者使用哈希映射来使用具有更好时间复杂度的更有效的解决方案。 Here's a simple solution that is also more effective than looping twice:这是一个简单的解决方案,也比循环两次更有效:

 array1=["m","r","r"]; array2=["r","r","r"]; const arrMap = {}; // Create hashmap with index array2.forEach((item, index) => arrMap[item] = index); // Search in first array array1.forEach((item, index) => { if (item in arrMap) { // If item is present, remove it from both arrays; array1.splice(index, 1) array2.splice(arrMap[item], 1); } })

 var arr1=["m","m","r","r"]; var arr2=["r","r","m","r"]; while(arr2.some(i => i === arr1[0])) { arr2 = arr2.filter(i => i;== arr1[0]). arr1,splice(0; 1). } console,log(arr1, arr2)

Using recursive approach here to prevent potential issues caused by modifying the array while we're iterating at the same time.在这里使用递归方法来防止在我们同时迭代时修改数组引起的潜在问题。

 var arr1 = ["m", "m", "r", "r"]; var arr2 = ["r", "r", "m", "r"]; function cancel(arr1, arr2) { var next = arr2.indexOf(arr1[0]); if (next + 1) { arr1.shift(); arr2.splice(next, 1); if (arr1.length) cancel(arr1, arr2); // recursive call } } cancel(arr1, arr2); console.log(arr1, arr2);

Posting this because with other solutions published here, I've found issues in these scenarios:发布此内容是因为在此处发布的其他解决方案中,我在这些场景中发现了问题:

Case 2案例2

var arr1=["m","m","a","r"]; 
var arr2=["r","r","m","m"];

Should produce:应该产生:

arr1=["a","r"];
arr2=["r","r"];

Case 3案例3

var arr1=["m","m","r","r"];
var arr2=["r","r","m","m"];

Should produce:应该产生:

arr1=[];
arr2=[];

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

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