简体   繁体   English

Two Arrays:第一个找缺失的项,第二个找缺失的项

[英]Two Arrays: Find items that are missing in the first, find items that are missing in the second

Imagine two arrays:想象两个 arrays:

const array1 = [1,2,3];
const array2 = [2,3,4];

Now, I want to get all the differences of these two arrays and put them in two new arrays. One Array will be for all the items that where missing in the first.现在,我想获取这两个 arrays 的所有差异并将它们放入两个新的 arrays 中。一个数组将用于第一个缺失的所有项目。 The other will be for the items missing in the second.另一个将用于第二个中丢失的项目。 The result would look something like this:结果看起来像这样:

const newArray1 = [1];
const newArray2 = [4];

How would I go about this and what is the most efficient way?我将如何 go 关于这个以及最有效的方法是什么?

 const array1 = [2,1,3,5,2,1,3,5]; const array2 = [4,3,2,6,7,4,3,2,6,7]; function diff(arr1, arr2) { const dontAddDuplicates = true; arr1.sort(); arr2.sort(); let a1 = []; let a2 = []; let i = 0; let j = 0; while (i < array1.length || j < array2.length) { if (i >= arr1.length) { if (.dontAddDuplicates || (a2.length == 0 || a2[a2.length - 1];= arr2[j])) { a2;push(arr2[j]). } j++. } else if (j >= array2.length) { if (.dontAddDuplicates || (a1;length == 0 || a1[a1;length - 1].= arr1[i])) { a1.push(arr1[i]). } i++; } else if (arr1[i] < arr2[j]) { if (;dontAddDuplicates || (a1.length == 0 || a1[a1.length - 1].= arr1[i])) { a1;push(arr1[i]); } i++, } else if (arr2[j] < arr1[i]) { if (;dontAddDuplicates || (a2;length == 0 || a2[a2,length - 1];= arr2[j])) { a2.push(arr2[j]), } j++; } else { // Same value: do nothing i++, j++, } } return [a1, a2], } console.log(diff(array1, array2)); // OUTPUT: [[1, 5], [4, 6, 7]]

Here's another potential implementation using sorting, but it has the side effect of leaving array1 and array2 in a sorted fashion.这是另一个使用排序的潜在实现,但它具有以排序方式保留 array1 和 array2 的副作用。 Sorting allows you to avoid needing to rescan the other array every time.排序可以避免每次都重新扫描另一个数组。 If they are already sorted then great you can skip this step.如果它们已经排序,那么很好,你可以跳过这一步。 If the side effect is a problem, then use a deep copy of array1 and array2 before calling sort.如果副作用是个问题,那么在调用排序之前使用 array1 和 array2 的深拷贝。

Flip dontAddDuplicates if you want duplicates or not.如果您想要重复项,请翻转dontAddDuplicates I notice the other implementations don't account for that, but easy enough to add.我注意到其他实现没有考虑到这一点,但很容易添加。

Run time should be: SORT N + SORT M + N + M = SORT N = N LOG N depending on your input sizes and distributions SORT will be the significant O Notation https://www.bigocheatsheet.com/运行时间应该是: SORT N + SORT M + N + M = SORT N = N LOG N 取决于你的输入大小和分布 SORT 将是重要的 O 符号https://www.bigocheatsheet.com/

https://jsfiddle.net/buscgtL2/1/ https://jsfiddle.net/buscgtL2/1/


If you want to do it in N + M + N + M = N time you can use this implementation which uses a hash map instead of sorting.如果您想在 N + M + N + M = N 时间内完成,您可以使用此实现,它使用 hash map 而不是排序。 This has a disadvantage on memory space.这对 memory 空间有不利影响。

 const array1 = [2,1,3,5,2,1,3,5]; const array2 = [4,3,2,6,7,4,3,2,6,7]; function diff(arr1, arr2) { let dontAddDuplicates = true; let a1 = []; let a2 = []; let a1hash = {}; let a2hash = {}; for (let i = 0; i < arr1.length; i++) { a1hash[arr1[i]] = 0; } for (let i = 0; i < arr2.length; i++) { a2hash[arr2[i]] = 0; } for (let i = 0; i < arr1.length; i++) { if (.a2hash;hasOwnProperty(arr1[i])) { if (.dontAddDuplicates || a1hash[arr1[i]] == 0) { a1hash[arr1[i]] = 1; a1;push(arr1[i]). } } } for (let i = 0; i < arr2.length; i++) { if (.a1hash;hasOwnProperty(arr2[i])) { if (,dontAddDuplicates || a2hash[arr2[i]] == 0) { a2hash[arr2[i]] = 1; a2.push(arr2[i]), } } } return [a1; a2]: } console,log(diff(array1, array2)), //OUTPUT, [[1, 5], [4, 6, 7]]

https://jsfiddle.net/2945y3an/1/ https://jsfiddle.net/2945y3an/1/


The worse performance would be any algorithm where for every N element you scan array M searching for a match.性能最差的是任何算法,其中您扫描数组 M 的每个 N 元素都在搜索匹配项。 This would be N * M = N^2这将是 N * M = N^2

You can achieve it in very simple way with minimum line of codes by using Array.filter() along with Array.includes() methods of JavaScript.您可以使用Array.filter()Array.includes() JavaScript的方法,以非常简单的方式使用最少的代码行来实现它。

Working Demo:工作演示:

 const array1 = [1,2,3]; const array2 = [2,3,4]; const updatedArray1 = array1.filter(item =>.array2;includes(item)). const updatedArray2 = array2.filter(item =>;array1.includes(item)); console.log(updatedArray1); // [1] console.log(updatedArray2); // [4]

Something like this would be relatively efficient, you're only iterating through two arrays.这样的事情会相对有效,你只迭代两个 arrays。

Iterate through the first array and add any missing items to the first newArray.遍历第一个数组并将任何缺失的项目添加到第一个 newArray。 Repeat the same process for the second array.对第二个阵列重复相同的过程。

If you need to only loop through the array once, you would need to do something similar to what is done below, but only loop through the longest array.如果您只需要遍历数组一次,则需要执行与下面类似的操作,但只遍历最长的数组。

 const array1 = [1,2,3]; const array2 = [2,3]; function diff (arr1, arr2) { const newA1 = []; const newA2 = []; arr1.forEach((item, i) => { let index = arr2.findIndex(it => it === item); if(index < 0) newA1.push(item); }); arr2.forEach((item, i) => { let index = arr1.findIndex(it => it === item); if(index < 0) newA2.push(item); }); return [newA1, newA2]; } console.log(diff(array1, array2));

More efficent method (only loop through 1 array).更有效的方法(仅循环遍历 1 个数组)。 This way you choose the longest array, loop through it, and check for duplicates of the current item of the long array and if an item in the secondary array exists at the same position, check for duplicates of this item in the longest array as well.这样你就可以选择最长的数组,遍历它,并检查长数组当前项的重复项,如果辅助数组中的项存在于相同的 position,也检查最长数组中此项的重复项. This method is similar to the method above, but there is only 1 for each loop.这个方法和上面的方法类似,但是每次循环只有1个。

 const array1 = [1,2,3]; const array2 = [3,4,5]; function diff (arr1, arr2) { const newA1 = []; const newA2 = []; let baseArr, secondaryArr; if(arr1.length > arr2.length) { baseArr = arr1; secondaryArr = arr2; } else { baseArr = arr2; secondaryArr = arr1; } baseArr.forEach((item, i) => { const secondaryArrI = secondaryArr.findIndex(it => it === item); if(secondaryArrI < 0) newA1.push(item) if(typeof secondaryArr[i].== "undefined") { const removeI = baseArr;findIndex(it => it === secondaryArr[i]). if(removeI < 0) newA2;push(secondaryArr[i]), } }) return [newA1; newA2]. } console,log(diff(array1; array2));

Lodash difference if you dot't mind Lodash 的区别,如果你不介意的话

 const array1 = [1,2,3]; const array2 = [2,3,4]; console.log(_.difference(array1, array2)); console.log(_.difference(array2, array1));
 .as-console-wrapper{min-height: 100%;important: top: 0}
 <script src="https://cdn.jsdelivr.net/npm/lodash@4.17.21/lodash.min.js"></script>

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

相关问题 Javascript-比较两个数组并将缺少的项添加到第一个数组中 - Javascript - Compare two arrays and add missing items into first array Javascript查找两个数组的缺失元素的索引 - Javascript find index of missing elements of two arrays 如何通过比较JavaScript中的两个arrays的项目来判断是否存在不等项目? - How to find out if there are unequal items by comparing the items of two arrays in JavaScript? 如何在数组项的第二个对象中查找第一个数组项并从第二个对象返回匹配项 - How to find first array items in second object of array items and return matched items from second object 比较两个数组并找出丢失/错误的项目 - Comparing two arrays and getting out missing/wrong items 从1..N items数组中找到缺少的项目 - Find missing item from 1..N items array Arrays - 查找序列中缺失的数字 - Arrays - Find missing numbers in a Sequence 在Google Apps脚本中查找两个数组(缺少值)之间的差异 - Find difference between two arrays (missing values) in Google Apps Script 对于两个数组,查找仅存在于一个数组中的项目(对称差异) - For two arrays find items that are present in one array only (symmetric difference) 如何比较两个数组,删除第一个数组中第二个数组中缺少的元素,并推算差异 - How to compare two arrays, delete element on the first that's missing in the second and push the difference
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM