Brian Smith
Brian Smith

Reputation: 11

Filter object in javascript

I am trying to filter through an array of objects and delete one of the object but keep the rest inside an array of objects but i keep returning either an array of arrays or i create nested objects. Is it possible to send in an array of objects and return and array of objects without that specific object? Below is the code I have been trying to work with.

      function deleteWorkout(workoutName) {
    
    const updatedArray = myWorkoutToDisplay.map((item) => item.newWorkToAdd.filter((workout) => workout.name !== workoutName))
    const objectArray = [{updatedArray}]
    const newWorkToAdd = objectArray.filter(e => e.length)
    const workouts = [{newWorkToAdd}]
    setMyWorkoutToDisplay(updatedArray)
  }

Upvotes: 0

Views: 102

Answers (1)

MrMythical
MrMythical

Reputation: 9041

You can easily do this with Array.prototype.filter. I guess the easiest way to delete 1 object is like this:

//let arr = arrayLike
//let objToDelete = whatever you want to delete
let newArr = arr.filter(obj => obj !== objToDelete)

newArr now has the array, without the deleted item. arr however still has it. To delete item by index, use this:

//let arr = arrayLike
//let ind = index to delete
let newArr = arr.filter((_, index) => index !== ind)

Upvotes: 1

Related Questions