【问题标题】:Remove duplicates from Array with Objects使用对象从数组中删除重复项
【发布时间】:2020-01-17 19:00:56
【问题描述】:

我有这样的事情:

  items: { _id: number; place: SomeAddressClassDto }[] = [];
  sessionItem: { _id: number; place: SomeAddressClassDto };

  createAddressList() {

    this.service.getWorkingPlaces().subscribe((items) => {
      this.items = items;

      this.sessionItem = {
        place: JSON.parse(sessionStorage.getItem('currentPlace')),
        _id: this.items.length,
      };

      this.items.push(this.sessionItem);

    // _.uniqBy(this.items, 'place')

      const idx = items.findIndex((item) => this.service.comparePlaces(item.place, 
 this.service.getCurrentWorkingPlace()));
      if (idx !== -1) this.radiobox.option = `${idx}`;
    });
  }

我正在尝试使用 _uniqBy 方法从“items”数组中删除所有重复项,但它不起作用。我认为这是因为对于这个 items._id 总是不同但 items.place 可能是相等的,如果是我想摆脱这个。

也许更好的方法是检查是否相同的 items.place 已经在该数组中,但不知道如何执行此操作。

编辑: 具体来说,项目如下所示:

0: place: {name, street, city, etc...}
   _id: 0

因此,可能有非常相似的对象,但只有一个属性不同{}

【问题讨论】:

    标签: javascript arrays angular typescript object


    【解决方案1】:

    我建议使用_id 来确定该值是否唯一。如果您使用place,则该值可能始终是唯一的,因为它们可能是同一类的不同实例。(如果是这种情况,我无法从您的代码中判断)

    createAddressList() {
        this.service.getWorkingPlaces().subscribe((items) => {
            this.items = items;
    
            this.sessionItem = {
                place: JSON.parse(sessionStorage.getItem('currentPlace')),
                _id: this.items.length,
            };
    
            this.items.push(this.sessionItem);
    
            _.uniqBy(this.items, '_id');
    
            const idx = items.findIndex((item) => this.service.comparePlaces(item.place, this.service.getCurrentWorkingPlace()));
            if (idx !== -1) {
                this.radiobox.option = `${idx}`;
            }
        });
    }
    

    或者,您可以使用 place 内部的属性来确定它们是否是唯一的,如下所示:

     _.uniqBy(this.items, (x) => x.place && x.place.someOtherPropertyInsideOfPlace);
    

    【讨论】:

      【解决方案2】:

      您可以使用Array.Prototype.reduce()Array.prototype.find() 根据place 属性创建一个没有重复项的数组。

      举个例子:

      const test = [
        { _id: 1, place: 'a' },
        { _id: 2, place: 'a' },
        { _id: 3, place: 'a' },
        { _id: 4, place: 'b' },
        { _id: 5, place: 'c' },
      ]
      
      const noDups = test.reduce((accum, current)=> {
        if(!accum.find(item => item.place === current.place))
          accum.push(current)
        return accum
      }, [])
      console.log(noDups)
      

      reduce() 将创建一个新数组(在这种情况下,accum 变量被初始化为一个空数组),但如果.place 属性是唯一的,则仅在新数组中添加新项,如果它尚未找到具有相同 .place 属性的项目

      【讨论】:

        【解决方案3】:
        • 用 id 和 place 属性声明一个简单的对象数组。

        • 通过 javascript 过滤功能删除重复项。

        • filter 函数会从数组中删除位置为 paris 的对象。

        var arr = [{
            _id: 1,
            place: 'paris'
          },
          {
            _id: 2,
            place: 'tokyo'
          },
          {
            _id: 3,
            place: 'ontario'
          },
          {
            _id: 4,
            place: 'paris'
          },
          {
            _id: 5,
            place: 'karachi'
          },
          {
            _id: 6,
            place: 'paris'
          },
          {
            _id: 7,
            place: 'new york'
          }
        ];
        
        var newArray = arr.filter((self, item, index) => index.findIndex(t => (t.place === self.place)) === item);
        
        console.log(newArray);

        【讨论】:

          猜你喜欢
          • 2017-04-10
          • 2016-03-12
          • 1970-01-01
          • 2019-02-28
          • 1970-01-01
          相关资源
          最近更新 更多