简体   繁体   中英

Iterate through object array and filter it based on multiple conditions

I have object array which contains a lot of duplicate/useless data. I need to filter based on customer id and pick the object with the latest date. The data looks something like this:

let data = [
  {
    CUSTOMER_PERMANENT_ID: "2495",
    EMAIL: "abs@gmail.com",
    EVENT_ACTIVATION_TIME: "2019-10-25 13:57:38.79",
  },
  {
    CUSTOMER_PERMANENT_ID: "2495",
    EMAIL: "abs@gmail.com",
    EVENT_ACTIVATION_TIME: "2019-10-28 20:04:49.016",
  },
  {
    CUSTOMER_PERMANENT_ID: "2495",
    EMAIL: "abs@gmail.com",
    EVENT_ACTIVATION_TIME: "2019-10-28 20:04:49.019",
  },
  {
    CUSTOMER_PERMANENT_ID: "5995",
    EMAIL: "John@gmail.com",
    EVENT_ACTIVATION_TIME: "2019-10-28 17:24:10.98",
  }
]

I have tried the following function, but it only works if there are two duplicate objects, if there are more than two it return all the objects.

public fixDcppSelectedClientData() {
    let result = [];

    for (let item of this.arr) {
      for (let checkingItem of this.arr) {
        if (
          this.arr.indexOf(item) !=
            this.arr.indexOf(checkingItem) &&
          item.CUSTOMER_PERMANENT_ID == checkingItem.CUSTOMER_PERMANENT_ID &&
          new Date(item.EVENT_ACTIVATION_TIME).getTime() <
            new Date(checkingItem.EVENT_ACTIVATION_TIME).getTime()
        ) {
          if (result.indexOf(checkingItem) == -1) {
            result.push(checkingItem);
          }
        }
      }
    }
    console.log("filtered data is ", result);
  }

I need to study this topic way more, however if anyone can help in the meantime it would be great.

Regards

let id = "2495"
const query = data
    .filter( obj => obj.CUSTOMER_PERMANENT_ID === id )
    .sort( (obj1, obj2) => 
        (obj1.EVENT_ACTIVATION_TIME < obj2.EVENT_ACTIVATION_TIME) ? 1 : -1 
    )

console.log('latest', query[0]);
console.log('second to latest', query[1]);
console.log('all with this id', query)

this code filter duplicates id

 var newArr = data.filter((x, index, self) => index === self.findIndex((t) => ( t.CUSTOMER_PERMANENT_ID === x.CUSTOMER_PERMANENT_ID))); console.log(newArr);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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