Home > Software engineering >  When I try to delete a specified array using indexOf and splice, another value is deleted
When I try to delete a specified array using indexOf and splice, another value is deleted

Time:04-10

What we want to solve

I manage my values with Vuex. I want to delete a given value in the events array and I tried to delete the value using indexOf and splice, but it deletes another value on the screen. On the server side, the value is deleted successfully, so reloading the server returns the correct value.

Is there a mistake in the value specified for indexOf and splice? I'd like to know what caused this and how to fix it.

# Code

Array Data

// I want to delete a specified value from an array containing a large amount of data.
[0 … 99]
[100 … 199]
[200 … 250]

0:
color: "#2196F3"
end: 1649116800000
id: 7
long_time: true
name: ""
post_id: null
start: 1649115900000
timed: true
updated_at: "2022-04-05T08:44:01.049 09:00"
・
・
・
・

store

export const state = () => ({
  events: [],

})

export const mutations = {

    deleteEvent(state, payload) {
    state.events.splice(state.events.indexOf(payload), 1)
  },
}

export const actions = {
  deleteEvent ({ rootState, commit }, event) {
    this.$axios.$delete(`${url.SCHEDULE_API}/${event.id}`)
    .then(() => {

      commit('deleteEvent', event)
・
・
・
・
      })

  },
}


** components**

// selectedEvent
{
color: (...)
created_at: (...)
end: (...)
id: (...)
long_term_id: (...)
long_time: (...)
name: (...)
post_id: (...)
start: (...)
timed: (...)
updated_at: (...)
}
methods: {
    deleteEvent (event) {
      this.selectedOpen = false
      this.$store.dispatch('schedule/deleteEvent', this.selectedEvent)
    },
}

CodePudding user response:

Array.prototype.indexOf() looks up an array element by its value using strict equality. This only works with primitive values.

Since state.events[] contains an array of objects (not primitive), indexOf() returns -1 because the non-primitive cannot be found. Passing a -1 index to Array.prototype.splice() removes the last element, leading to the behavior you observed.

Solution

To lookup an object in the array, use Array.prototype.findIndex() with a callback that compares its argument's id property (or some other unique identifier) to that in the payload:

const index = state.events.findIndex(event => payload.id === event.id)
if (index > -1) {
  state.events.splice(index, 1)
}
  • Related