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

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

问题描述

我有两个 JavaScript 数组(AB),其中包含我创建的对象.我想检查数组 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.

最好的方法是什么?

它们都是实际的对象,而不是基元,所以我还需要比较它们的内容和结构(可能使用类似 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 Arrays - 检查两个对象数组的相同内容,忽略顺序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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