有没有办法检查两个数组是否具有相同的元素?
16lz
2021-01-22
Let say I have 2 arrays
假设我有2个阵列
firstArray = [1, 2, 3, 4, 5];
secondArray = [5, 4, 3, 2, 1];
I want to know if they contain the same elements, while order is not important. I know I can write a function to sort them and then loop through them to check, but is there a pre-built function for this? (not only Vanilla JS, other javascript library is also okay)
我想知道它们是否包含相同的元素,而顺序并不重要。我知道我可以编写一个函数来对它们进行排序,然后循环遍历它们进行检查,但是有没有预先构建的函数呢? (不仅是Vanilla JS,其他javascript库也没关系)
4 个解决方案
#1
4
Using jQuery
You can compare the two arrays using 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 );
Here is a JsFiddle Demo
这是一个JsFiddle演示
See this question helpful answer
看到这个问题有用的答案
更多相关文章
- JavaScript循环输入创建一个对象数组
- JavaScript数组操作函数方法详解
- 数组多重排序
- ES6学习笔记二之数组的扩展
- 在关联数组中移动元素[重复]
- JavaScript——数组(三)数组方法汇总
- 如何通过ajax将javascript数组传递给YII动作
- 在Javascript中将带有空格的字符串数组转换为小写,然后在Webkit中
- 返回指定时间段相同间隔数组