Christopher Ducote
Christopher Ducote

Reputation: 333

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
}

Upvotes: 0

Views: 1090

Answers (4)

marzelin
marzelin

Reputation: 11600

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
}

Upvotes: 0

Andre Nuechter
Andre Nuechter

Reputation: 2255

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

Upvotes: 0

Nina Scholz
Nina Scholz

Reputation: 386550

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

Upvotes: 1

Derek Lawrence
Derek Lawrence

Reputation: 1608

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

Upvotes: 0

Related Questions