简体   繁体   中英

Comparing Elements of two Arrays in javascript

I have 2 arrays like below

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

and I want to compare both the arrays.

If the first element of array1 (which is "m" ) is present in array2 then remove both the elements from both the array. then arrays should become as below

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. However, if the first element from updated array1 is not present in updated array2 then break the statement.

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

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

Should produce:

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

Case 3

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

Should produce:

arr1=[];
arr2=[];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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