简体   繁体   English

检查JavaScript中两个数组的值是否相同/相等的最佳方法

[英]Best way to check if values of two arrays are the same/equal in JavaScript

What is the best way to check if two arrays have the same/equal values (in any order) in JavaScript? 检查两个数组在JavaScript中是否具有相同/相等值(以任何顺序)的最佳方法是什么?

These values are just a primary keys of database entities, so they always will be different 这些值只是数据库实体的主键,因此它们总是会有所不同

const result = [1, 3, 8, 77]
const same = [8, 3, 1, 77]
const diff = [8, 3, 5, 77]

areValuesTheSame(result, same) // true
areValuesTheSame(result, diff) // false

How should areValuesTheSame method look like? areValuesTheSame方法应如何areValuesTheSame

PS This question looks like a duplicate but I didn't find anything relative to Javascript. PS这个问题看起来像一个重复,但是我没有找到任何有关Javascript的东西。

I'm making the following assumptions: 我做以下假设:

  • The arrays only contain numbers. 数组仅包含数字。
  • You don't care about the order of the elements; 您不在乎元素的顺序; rearranging the arrays is OK. 重新排列数组就可以了。

Under those conditions we can simply convert each array to a canonical string by sorting it and joining the elements with eg a space. 在这些条件下,我们可以通过将每个数组排序并将元素与例如空格连接的方式,将每个数组简单地转换为规范字符串。 Then (multi-)set equality boils down to simple string equality. 然后,(多)集相等可归结为简单字符串相等。

 function areValuesTheSame(a, b) { return a.sort().join(' ') === b.sort().join(' '); } const result = [1, 3, 8, 77]; const same = [8, 3, 1, 77]; const diff = [8, 3, 5, 77]; console.log(areValuesTheSame(result, same)); console.log(areValuesTheSame(result, diff)); 

This is probably the laziest / shortest approach. 这可能是最懒/最短的方法。

You could count all elements with a Map (this is type save) up for the one array and down for the other and check if all items have a final count of zero. 您可以使用一个Map所有元素(这是类型保存),为一个数组递增计数,为另一个数组递减计数,并检查所有项目的最终计数是否为零。

 function haveSameValues(a, b) { const count = d => (m, v) => m.set(v, (m.get(v) || 0) + d) return Array .from(b.reduce(count(-1), a.reduce(count(1), new Map)).values()) .every(v => v === 0); } const result = [1, 3, 8, 77] const same = [8, 3, 1, 77] const diff = [8, 3, 5, 77] console.log(haveSameValues(result, same)); // true console.log(haveSameValues(result, diff)); // false 

Try this: 尝试这个:

 const result = [1, 3, 8, 77] const same = [8, 3, 1, 77] const diff = [8, 3, 5, 77] const areValuesTheSame = (a,b) => (a.length === b.length) && Object.keys(a.sort()).every(i=>a[i] === b.sort()[i]) console.log(areValuesTheSame(result, same)) // true console.log(areValuesTheSame(result, diff)) // false 

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

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