简体   繁体   English

比较两个数组中元素的相等性

[英]Comparing equality of elements in two arrays

I have an assignment where I am supposed to check two arrays (unsorted) with integers, to see if 我有一个任务,我应该用整数检查两个数组(未排序),看看是否

  1. They have the same length 它们的长度相同
  2. The first element contains integers and the second has the same values squared, in any order 第一个元素包含整数,第二个元素以任何顺序具有相同的平方值

For example: 例如:

test([5,4,1], [1,16,25]) // would return true ..

What I've done so far is first sort the two input arrays, and then compare the length. 到目前为止我所做的是首先对两个输入数组进行排序,然后比较长度。 Once we confirm the length is the same we iterate through each value to make sure they're equal. 一旦我们确认长度是相同的,我们迭代每个值以确保它们是相等的。 Keep in mind I haven't gotten to comparing the values to their squared counterpart yet, because my loop is not giving me expected results. 请记住,我还没有将值与它们的平方对应物进行比较,因为我的循环没有给出预期的结果。 Here is the code: 这是代码:

function test(arr1, arr2){
  // sort arrays
  const arr1Sort = arr1.sort(),
        arr2Sort = arr2.sort();

  // compare length and then compare values
  if(arr1Sort.length === arr2Sort.length) {
    for(let i = 0; i < arr1Sort.length; i++) {
      if(arr1Sort[i] === arr2Sort[i]) {
        return true;
      } else {
        return false;
      }
    }
  }
}

console.log(test([1,2,3], [1,5,4])); returns true but the array values are different?!

Inside the for , no matter whether the if or else is fulfilled, the function will immediately return true or false on the first iteration - it'll never get past index 0 . for ,无论是否满足ifelse函数将在第一次迭代时立即返回truefalse - 它永远不会超过索引0 To start with, return true only after the loop has concluded, and return false if arr1Sort[i] ** 2 !== arr2Sort[i] (to check if the first squared equals the second). 首先, return true循环已经结束后才return false如果arr1Sort[i] ** 2 !== arr2Sort[i]以检查第一平方等于第二)。

Also, when sorting, make sure to use a callback function to compare each item's difference , because otherwise, .sort will sort lexiographically (eg, [1, 11, 2] ): 此外,在排序时,请确保使用回调函数来比较每个项目的差异 ,否则, .sort将按字母顺序排序(例如, [1, 11, 2] 1,11,2 [1, 11, 2] ):

 function comp(arr1, arr2){ // sort arrays const sortCb = (a, b) => a - b; const arr1Sort = arr1.sort(sortCb), arr2Sort = arr2.sort(sortCb); // compare length and then compare values if(arr1Sort.length !== arr2Sort.length) { return false; } for(let i = 0; i < arr1Sort.length; i++) { if(arr1Sort[i] ** 2 !== arr2Sort[i]) { return false; } } return true; } console.log(comp([1,2,3], [1,5,4])); console.log(comp([5,4,1], [1,16,25])); 

You can decrease the computational complexity to O(N) instead of O(N log N) by turning arr2 into an object indexed by the squared number beforehand: 您可以通过将arr2转换为预先由平方数索引的对象,将计算复杂度降低到O(N)而不是O(N log N)

 function comp(arr1, arr2){ if (arr1.length !== arr2.length) { return false; } const arr2Obj = arr2.reduce((a, num) => { a[num] = (a[num] || 0) + 1; return a; }, {}); for (let i = 0; i < arr1.length; i++) { const sq = arr1[i] ** 2; if (!arr2Obj[sq]) { return false; } arr2Obj[sq]--; } return true; } console.log(comp([1,2,3], [1,5,4])); console.log(comp([5,4,1], [1,16,25])); 

(if duplicates weren't permitted, this would be a lot easier with a Set instead, but they are, unfortunately) (如果不允许重复,那么使用Set会更容易,但不幸的是,它们很简单)

This should work, no mater the data to compare: 这应该工作,无需比较数据:

 function similar(needle, haystack, exact){ if(needle === haystack){ return true; } if(needle instanceof Date && haystack instanceof Date){ return needle.getTime() === haystack.getTime(); } if(!needle || !haystack || (typeof needle !== 'object' && typeof haystack !== 'object')){ return needle === haystack; } if(needle === null || needle === undefined || haystack === null || haystack === undefined || needle.prototype !== haystack.prototype){ return false; } var keys = Object.keys(needle); if(exact && keys.length !== Object.keys(haystack).length){ return false; } return keys.every(function(k){ return similar(needle[k], haystack[k]); }); } console.log(similar(['a', {cool:'stuff', yes:1}, 7], ['a', {cool:'stuff', yes:1}, 7], true)); // not exact console.log(similar(['a', {cool:'stuff', yes:1}, 7], ['a', {cool:'stuff', stuff:'more', yes:1}, 7, 'more stuff only at the end for numeric array'])); 

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

相关问题 比较两个 arrays javascript 中的元素 - comparing elements in two arrays javascript 比较 javascript 中两个 Arrays 的元素 - Comparing Elements of two Arrays in javascript Angular.js比较两个数组中的元素 - Angularjs comparing elements from two arrays 比较两个 arrays 并返回有效和错位的元素 - Comparing two arrays and returning valid and misplaced elements 在javascript中比较两个数组,并使用缺少的元素和新的元素创建新的数组 - Comparing two arrays in javascript and creating new arrays with missing and new elements 通过比较具有不同元素的两个对象数组来过滤和删除项目 - Filter and delete items by comparing two arrays of objects with different elements 如何通过比较对象的两个数组与对象中不同元素的方法来过滤数组? - How to filter array by comparing two arrays of objects with different elements in their objects? 获取在Java中比较两个或多个数组的Common和Uniques元素 - Get the Common and Uniques Elements Comparing two or more arrays in Javascript 比较两个不同长度的数组,并返回包含不常见元素的数组 - comparing two arrays of different lengths and returning an array with the uncommon elements 在Prototype中比较两个元素是否相等 - Compare two elements for equality in Prototype
 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM