JavaScript数组 - 检查内容相同对象的两个数组,无视秩序 [英] Javascript Arrays - Checking two arrays of objects for same contents, ignoring order

查看:142
本文介绍了JavaScript数组 - 检查内容相同对象的两个数组,无视秩序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个JavaScript数组包含我创建的对象( A B )。我要检查,在阵列中的所有对象 A 包含在阵列 B ,但不一定以相同的顺序

I have two JavaScript arrays (A and B) that contain objects that I created. I want to check that all the objects in array A are contained in array B, but not necessarily in the same order.

什么是做到这一点的最好方法是什么?

What is the best way to do this?

编辑:

他们都是实际的对象,而不是原语,所以我需要他们的内容和结构进行比较,同时(可能使用类似 JSON.stringify )。

They are all actual objects, not primitives, so I will need to compare their contents and structure as well (maybe using something like JSON.stringify).

我想这样做,因为我学习测试驱动开发,我想测试返回对象的列表功能。我需要测试返回列表中是否有他们或预期的对象不是(顺序并不在这种情况下问题)。

I want to do this because I'm learning Test-Driven Development, and I want to test functions that return lists of objects. I need to test whether the returned lists have the expected objects in them or not (order doesn't matter in this case).

推荐答案

用法: isEqArrays(ARR1,ARR2)

//
// Array comparsion
//

function inArray(array, el) {
  for ( var i = array.length; i--; ) {
    if ( array[i] === el ) return true;
  }
  return false;
}

function isEqArrays(arr1, arr2) {
  if ( arr1.length !== arr2.length ) {
    return false;
  }
  for ( var i = arr1.length; i--; ) {
    if ( !inArray( arr2, arr1[i] ) ) {
      return false;
    }
  }
  return true;
}

这篇关于JavaScript数组 - 检查内容相同对象的两个数组,无视秩序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆