1

Imagine I've got an array of objects like so (dummy code):

const chosenBets = [{...}, {...}] // 2 items

And I want to delete a specific item from the array:

{id: 0, // is unique
 label: 1,
 odd: 1.33,
 oddIndex: 0,
 team_home: "Liverpool",
 team_away: "Sheffield United",
 matchCardIndex: 0,}

So that array is now:

const chosenBets = [{...}] // 1 items

How would I achieve this?

3 Answers 3

5

You can use array filter

const chosenBets = [{
  id: 0, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}, {
  id: 1, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}];

const filteredData = chosenBets.filter(item => item.id === 1);
console.log(filteredData);

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

Comments

1

You can use splice

var a = [{
    id: 0, // is unique
    label: 1,
    odd: 1.33,
    oddIndex: 0,
    team_home: "Liverpool",
    team_away: "Sheffield United",
    matchCardIndex: 0,
  },
  {
    id: 0, // is unique
    label: 11,
    odd: 1.33,
    oddIndex: 0,
    team_home: "Liverpool",
    team_away: "Sheffield United",
    matchCardIndex: 0,
  }
]
a.forEach((e, j) => {
  if (e.label == 1)
    a.splice(j, 1);
})
console.log(a)

Comments

0

If you want to delete a specific and unique object, I would do something like:

let chosenBets = [{
  id: 0, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}, {
  id: 1, // is unique
  label: 1,
  odd: 1.33,
  oddIndex: 0,
  team_home: "Liverpool",
  team_away: "Sheffield United",
  matchCardIndex: 0
}];

let index = chosenBets.findIndex(({id}) => id === 1);

// if you want to mutate the original array, otherwise use `slice`
chosenBets.splice(index, 1);
console.log(chosenBets);

filter is better if you want to remove a group of elements, not just one. The reason is, it keeps going to iterate all the elements of the array, so it always iterate the whole array, even if the element you want to remove is the first one. Using findIndex you just iterate until you find the element, and then return the index: so as average, it does less cycle.

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.