0

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
}
1
  • 1
    do you have some data to illustrate the problem? Commented Oct 11, 2019 at 18:53

4 Answers 4

1

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

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

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

Comments

0

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
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.