【问题标题】:Is There Any Method To Push Object To Array Uniquely? [duplicate]有什么方法可以将对象唯一地推送到数组吗? [复制]
【发布时间】:2019-02-19 01:43:18
【问题描述】:

ES6 是否有任何方法可以通过 1 种方法将对象唯一地推送到数组?

例如:

MyArray.pushUniquely(x);

或者像旧版本一样好用? :

MyMethod(x) {

    if ( MyArray.IndexOf(x) === -1 )
        MyArray.Push(x);

}

ES6有什么方法可以唯一推送吗?

【问题讨论】:

  • 既然你用mongo-shell标记了这个,值得注意的是MongoDB有$.addToSet operator用于集合。
  • 在这种情况下我必须使用迭代查询。查询,然后获取一些 id,然后再次查询。最后,我必须将它们都减少为唯一的。

标签: javascript arrays ecmascript-6 mongo-shell


【解决方案1】:

使用Set 集合而不是数组。

var mySet = new Set([1, 2, 3]);

mySet.add(4);
mySet.add(3);
mySet.add(0)

console.log(Array.from(mySet))

【讨论】:

    【解决方案2】:

    使用includes(我已经扩展了一个方法,因此您可以在所有数组上使用它):

    Array.prototype.pushUnique(item) {
        if (!this.includes(item)) this.push(item);
    }
    

    或者,使用Set:

    mySet.add(x); //Will only run if x is not in the Set
    

    【讨论】:

      【解决方案3】:

      你可以使用 lodash uniq 方法。

      var uniq = _.uniq([1,2,3,4,5,3,2,4,5,1])
      
      console.log(uniq)
      <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

      【讨论】:

        【解决方案4】:

        如果数组是一个对象数组,你可以这样做

        const arr = [{
            name: 'Robert',
            age: 26
          },
          {
            name: 'Joshua',
            age: 69
          }
        ]
        
        Array.prototype.pushUniquely = function (item) {
          const key = 'name';
          const index = this.findIndex(i => i[key] === item[key]);
          if (index === -1) this.push(item);
        }
        
        arr.pushUniquely({
          name: 'Robert',
          age: 24
        });
        
        console.log(arr);

        如果它只是一个字符串或数字的数组,那么你可以这样做:

        Array.prototype.pushUniquely = function (item) {
            if (!this.includes(item)) this.push(item);
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2020-02-13
          • 2023-03-31
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多