【问题标题】:What is the best way to see if an array has two objects with the same values for two distinct properties?查看数组是否有两个对象的两个不同属性具有相同值的最佳方法是什么?
【发布时间】:2019-12-17 23:11:50
【问题描述】:

例如,我想看看这个数组是否有两个名字和姓氏相同的对象。

[{fName: Albert, lName: Anderson, age:42},

{fName: Albert, lName: Anderson, age:41},

{fName: Albert, lName: Bernard, age:42}]

将返回 true,因为第一个和第二个对象具有相同的 fName 和 lName。

我的第一个想法是创建一个Set,它接受一个只包含fName 和lName 对的对象,将每一对插入到Set 中并使用for 循环,然后比较@ 的大小987654326@到数组的大小看是否有重复。我想知道是否有更快或更好的方法来做到这一点

【问题讨论】:

    标签: javascript arrays duplicates set


    【解决方案1】:

    如果找到相同的模式,您可以使用 Set 并退出循环。

    function hasSame(array) {
        const getValueBy = keys => object => keys.map(k => object[k]).join('|');
    
        var seen = new Set,
            getV = getValueBy(['fName', 'lName']);
    
         return array.some(o => seen.has(getV(o)) || !seen.add(getV(o)));
    }
    
    var data = [{ fName: 'Albert', lName: 'Anderson', age: 42 }, { fName: 'Albert', lName: 'Anderson', age: 41 }, { fName: 'Albert', lName: 'Bernard', age: 42 }];
    
    console.log(hasSame(data));

    【讨论】:

      【解决方案2】:

      遍历数组,每次遍历数组再进行比较,count至少为1,因为每次都会有相同的对象,所以如果匹配更多,count会大于1

      for(let obj of arr) {
          let count = 0
          for(let obj2 of arr) {
              if(obj.fName == obj2.fName && obj.lName == obj2.lName) count++
          }
          if(count > 1) return true
      }
      return false
      

      【讨论】:

        【解决方案3】:

        您可以使用Map 和while 循环

        • 将newMap 初始化为Map 以跟踪fName 和lName
        • 将 dup 初始化为 false 以跟踪何时停止循环
        • 循环遍历数组,检查fName-lName 是否已经存在于newMap 中,然后将dup 设置为true,
        • 如果不是,则继续循环并继续将值添加到 newMap 直到数组的最后一个元素

        let obj = [{fName: 'Albert',lName: 'Anderson',age: 42},{fName: 'Albert',lName: 'Anderson',age: 41},{fName: 'Albert',lName: 'Bernard',age: 42}]
        
        let findIsDup = (obj) => {
          let newMap = new Map()
          let dup = false
          let index = 0
          while (!dup && index < obj.length) {
            let {fName,lName} = obj[index]
            let key = fName+ '-' + lName
            if (newMap.has(key)) {
              dup = true
            }
            index++
            newMap.set(key, key)
          }
          return dup
        }
        
        console.log(findIsDup(obj))
        console.log(findIsDup(obj.slice(1,)))

        【讨论】:

          【解决方案4】:
          function getDuplicatedItem(arr, compareFn) {
            return arr.slice(0).reduce(([_, ...rest], item, i, reducedArr) => {
              if (!rest.some(tmp => compareFn(item, tmp))) {
                return rest.length ? rest : false;
              }
          
              reducedArr.splice(0); // clean arr to "break" reduce
              return item;
            }, arr);
          }
          
          const arr = [
            { fName: "Albert", lName: "Anderson", age: 42 },
            { fName: "Albert", lName: "Anderson", age: 41 },
            { fName: "Albert", lName: "Bernard", age: 43 }
          ];
          
          const isSameFullName = (a, b) => a.fName == b.fName && a.lName == b.lName;
          const duplicatedItem = getDuplicatedItem(arr, isSameFullName)
          console.log(duplicatedItem) // { fName: 'Albert', lName: 'Anderson', age: 42 }
          
          const isSameAge = (a, b) => a.age == b.age
          const notFound = getDuplicatedItem(arr, isSameAge)
          console.log(notFound) // false
          

          【讨论】:

            【解决方案5】:

            您可以使用旧的 for 循环和内置 Array.prototype.some() 函数的一些帮助。

            您首先遍历数组中的每个对象,以将它们用作some() 函数的参数(或在本例中为搜索键)。 some()函数然后使用这个对象键来匹配数组中除自身之外的每个对象。

            some() 函数的优点是,当找到匹配项时,通过数组的迭代会立即停止并返回true。然后我们可以使用这个条件来终止外部的for 循环。

            var persons = [{fName: 'Albert', lName: 'Anderson', age:42}, {fName: 'Albert', lName: 'Anderson', age:41}, {fName: 'Albert', lName: 'Bernard', age:42}];
            
            console.log(hasDuplicate(persons));
            
            function hasDuplicate(persons) {
                for(var i=0; i<persons.length; i++) {
                    var isDuplicate = persons.some(function(duplicate, index) {
                        return i !== index && duplicate.fName === persons[i].fName && duplicate.lName === persons[i].lName
                    });
                    if (isDuplicate) return true;
                };
                return false;
            }

            【讨论】:

              猜你喜欢
              • 1970-01-01
              • 1970-01-01
              • 1970-01-01
              • 2021-11-03
              • 2021-08-19
              • 2014-02-03
              • 2016-09-15
              • 1970-01-01
              • 2012-12-31
              相关资源
              最近更新 更多