简体   繁体   English

使用对象从数组中删除重复项

[英]Remove duplicates from Array with Objects

I have something like this:我有这样的事情:

  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}`;
    });
  }

I am trying to remove any duplicates from 'items' array using the method _uniqBy, but it isn't working.我正在尝试使用 _uniqBy 方法从“items”数组中删除任何重复项,但它不起作用。 I think it's because for this items._id are always different but items.place could be equal and if are I would like to get rid of this.我认为这是因为对于这个 items._id 总是不同的但 items.place 可以是平等的,如果是我想摆脱这个。

Maybe better way is to check is the same items.place is already in that array, but no idea how to do this.也许更好的方法是检查相同的 items.place 是否已经在该数组中,但不知道如何执行此操作。

EDIT: To be more specify, items looks like this:编辑:更详细地说,项目如下所示:

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

So it is possible to have very similar object whitch is differnet only by one property in place{}因此,可能有非常相似的对象,而它们的不同之处仅在于一个属性的位置{}

I would suggest using the _id to determine if the value is unique.我建议使用_id来确定该值是否唯一。 If you use place the value may always be unique since they could be different instances of the same class.(I can't tell from your code if this is the case)如果您使用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}`;
        }
    });
}

Alternately, you could use a property from inside place to determine if they are unique like this:或者,你可以使用属性从内place ,以确定它们是否喜欢这个独特的:

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

You can use Array.Prototype.reduce() and Array.prototype.find() to create an array that has no duplicates based on the place property.您可以使用Array.Prototype.reduce()Array.prototype.find()根据place属性创建一个没有重复项的数组。

As an example:举个例子:

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() will create a new array (in this case, the accum variable is being initialized as an empty array), but only add new items in the new array if the .place property is unique, if it doesn't already find an item with the same .place property reduce()将创建一个新数组(在这种情况下, accum变量被初始化为一个空数组),但如果.place属性是唯一的,如果它尚未找到一个新数组,则仅在新数组中添加新项目具有相同.place属性的项目

  • declaring a simple object array with id and place properties.声明一个带有 id 和 place 属性的简单对象数组。

  • Removing duplicates by javascript filter function.通过 javascript 过滤功能删除重复项。

  • filter function will remove the objects from array whose place is paris. 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM