有没有办法检查两个数组是否具有相同的元素?

cyt*_*nny 6 javascript arrays

假设我有2个阵列

firstArray  = [1, 2, 3, 4, 5];
secondArray = [5, 4, 3, 2, 1];
Run Code Online (Sandbox Code Playgroud)

我想知道它们是否包含相同的元素,而顺序并不重要.我知道我可以编写一个函数来对它们进行排序,然后循环遍历它们进行检查,但是有没有预先构建的函数呢?(不仅是Vanilla JS,其他javascript库也没关系)

Mat*_*ebb 5

使用jQuery

您可以使用jQuery以下方法比较两个数组:

// example arrays:
var firstArray  = [ 1, 2, 3, 4, 5 ];
var secondArray = [ 5, 4, 3, 2, 1 ];

// compare arrays:
var isSameSet = function( arr1, arr2 ) {
  return  $( arr1 ).not( arr2 ).length === 0 && $( arr2 ).not( arr1 ).length === 0;  
}

// get comparison result as boolean:
var result = isSameSet( firstArray, secondArray );
Run Code Online (Sandbox Code Playgroud)

这是一个JsFiddle演示

看到这个问题有用的答案


cus*_*der 5

假设您有:

\n
const xs = [1,2,3];\nconst ys = [3,2,1];\n
Run Code Online (Sandbox Code Playgroud)\n

似乎有效:

\n
xs.every(x => ys.includes(x));\n//=> true\n
Run Code Online (Sandbox Code Playgroud)\n

但它会给你误报:

\n
const xs = [2,2,2];\nconst ys = [1,2,3];\n\nxs.every(x => ys.includes(x));\n//=> true\n\n// But\xe2\x80\xa6\nys.every(y => xs.includes(y));\n//=> false\n
Run Code Online (Sandbox Code Playgroud)\n

另一个例子:

\n
const xs = [2];\nconst ys = [1,2,3];\n\nxs.every(x => ys.includes(x));\n//=> true\n\n// But\xe2\x80\xa6\nys.every(y => xs.includes(y));\n//=> false\n
Run Code Online (Sandbox Code Playgroud)\n

我们可以比较两个数组的大小并快速退出,但从技术上讲,这两个数组确实包含相同的元素:

\n
const xs = [2];\nconst ys = [2,2,2];\n\nys.every(y => xs.includes(y));\n//=> true\n\nxs.every(x => ys.includes(x));\n//=> true\n
Run Code Online (Sandbox Code Playgroud)\n

我回答这个问题的方法是计算两个数组的唯一值集。

\n
const similar = (xs, ys) => {\n  const xsu = [...new Set(xs).values()]; // unique values of xs\n  const ysu = [...new Set(ys).values()]; // unique values of ys\n  return xsu.length != ysu.length ? false : xsu.every(x => ysu.includes(x));\n}\n\nsimilar([1,2,3],[3,2,1]);\n//=> true\n\nsimilar([2,2,2],[3,2,1]);\n//=> false\n\nsimilar([2],[3,2,1]);\n//=> false\n\nsimilar([2],[2,2,2]);\n//=> true\n\nsimilar([1,2,3],[4,5,6]);\n//=> false\n
Run Code Online (Sandbox Code Playgroud)\n