[英]Quickest way to check if 2 arrays contain same values in javascript
[英]Best way to check if values of two arrays are the same/equal in JavaScript
检查两个数组在JavaScript中是否具有相同/相等值(以任何顺序)的最佳方法是什么?
这些值只是数据库实体的主键,因此它们总是会有所不同
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
areValuesTheSame
方法应如何areValuesTheSame
?
PS这个问题看起来像一个重复,但是我没有找到任何有关Javascript的东西。
我做以下假设:
在这些条件下,我们可以通过将每个数组排序并将元素与例如空格连接的方式,将每个数组简单地转换为规范字符串。 然后,(多)集相等可归结为简单字符串相等。
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));
这可能是最懒/最短的方法。
您可以使用一个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
尝试这个:
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.