【问题标题】:How to check two arrays of object has the same property value or not? [duplicate]如何检查两个对象数组是否具有相同的属性值? [复制]
【发布时间】:2021-08-19 03:55:10
【问题描述】:

我有两个数组,想检查所有 ID 是否相同

let a = [
          {id:0, name:"test0"},
          {id:1, name:"test1"}
         ];

let b = [
          {id:0, name:"test0"},
          {id:1, name:"test1"}
         ];

上面的数组我们看到是相等的

和我这样累的方式

JSON.stringify(a) === JSON.stringify(b) => True

我阅读了JSON.stringify,如果我们有大数组,它会影响性能

那么还有其他方法可以获得相同的结果吗?

【问题讨论】:

    标签: javascript arrays reactjs typescript


    【解决方案1】:

    const areEqual = (a = [], b = []) => {
      // compare length of arrays
      if(a.length !== b.length) {
        return false;
      }
      // get sorted lists of ids
      const arr1 = a.map(({id}) => id).sort(), arr2 = b.map(({id}) => id).sort();
      // iterate over the arrays and compare, if at an index, items mismatch, return false
      for(let i = 0; i < arr1.length; i++) {
        if(arr1[i] !== arr2[i]) {
          return false;
        }
      }
      // if it passes all the items, return true
      return true;
    }
    
    console.log( 
      areEqual(
        [{id:0, name:"test0"}, {id:1, name:"test1"}], 
        [{id:0, name:"test0"}, {id:1, name:"test1"}]
      )
    );

    使用Set的另一种解决方案:

    const areEqual = (a = [], b = []) => {
      // compare length of arrays
      if(a.length !== b.length) {
        return false;
      }
      // get ids set in b
      const idsSetInB = new Set(b.map(({id}) => id));
      // iterate over a, and check if the id of an item is not in b
      for(let {id} of a) {
        if(!idsSetInB.has(id)) {
          return false;
        }
      }
      // if it passes all the items, return true
      return true;
    }
    
    console.log( 
      areEqual(
        [{id:0, name:"test0"}, {id:1, name:"test1"}], 
        [{id:1, name:"test1"}, {id:0, name:"test0"}]
      )
    );

    【讨论】:

    • 不错的代码。我会指出,任何解决方案都将是 O(N) 的性能。无论如何,更长的数组将需要更多的工作来处理。
    • 谢谢,编辑前的第一个答案有什么问题? _getIds(a).sort().join(',')
    • @OliverD 它可以工作,但我编辑了解决方案以防您也想检查类型。
    • 问题,每个数组中的 id 是唯一的吗?
    • @MajedBadawi 是的,它是独一无二的!
    猜你喜欢
    • 1970-01-01
    • 2012-12-31
    • 1970-01-01
    • 2015-01-25
    • 2015-08-24
    • 2023-03-26
    相关资源
    最近更新 更多