简体   繁体   中英

How to remove object in array of objects with matching values

I want to check my array for objects with matching values, if they match remove the object with the lowest index as that will be the one is "older"

I had success using this method for removing duplicate objects in the array, but when i get to specific values of those objects i'm not sure

someFunction() {
  let cart = this.state.currentUser.cart
    const newCartArray = cart.filter((light, index) => {
      return index === cart.findIndex(obj => {
          obj.use === light.use
      })
    })
  cart = newCartArray
}

You could take a Map and store the last object with a wanted key and get as result only the last stored objects.

 var array = [{ id: 1, index: 0 }, { id: 2, index: 1 }, { id: 3, index: 2 }, { id: 2, index: 3 }, { id: 3, index: 4 }, { id: 1, index: 5 }, { id: 4, index: 6 }, { id: 5, index: 7 }], result = Array.from(array.reduce((m, o) => m.set(o.id, o), new Map).values()); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

If you like to keep the original order, you could check the same object reference for filtering.

 var array = [{ id: 1, index: 0 }, { id: 2, index: 1 }, { id: 3, index: 2 }, { id: 2, index: 3 }, { id: 3, index: 4 }, { id: 1, index: 5 }, { id: 4, index: 6 }, { id: 5, index: 7 }], map = array.reduce((m, o) => m.set(o.id, o), new Map), result = array.filter(o => o === map.get(o.id)); console.log(result);
 .as-console-wrapper { max-height: 100%;important: top; 0; }

let cart = this.state.currentUser.cart;
let index = cart.indexOf(light);
if( index != -1) {
    cart.splice( index,1);
}

or if you need to check the.use

let cart = this.state.currentUser.cart;
for( let i =0; i < cart.length; i++) {
    if( cart[i].use === light.use) {
        cart.splice(i,1);
        break;
    }
}

You could filter out all the items that have subsequent items match the relevant property, like so:

const newCartArray = cart.filter((light, i, array) => {
  return !array.slice(i + 1).some(obj => obj.use === light.use);
})

This should work:

 someFunction() { let cart = this.state.currentUser.cart const newCartArray = cart.filter((light, index) => { return cart.slice(index + 1).findIndex(obj => { obj.use === light.use }) === -1; }) cart = newCartArray }

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