Search code examples
javascriptarraysobjectmutation

How does one remove elements from an array by a process that does mutate this array?


I have an array of objects like this one:

const jokes = [
  {jokeId: 255, jokeText: "había un borrachín en un boliche", categoryId: "284"},
  {jokeId: 243, jokeText: "había una borrachín en un boliche", categoryId: "284"},
  {jokeId: 554, jokeText: "había otro borrachín en un boliche", categoryId: "284"},
  {jokeId: 424, jokeText: "jodido loco el tipo", categoryId: "256"},
  {jokeId: 257, jokeText: "había un loco en el manicomio", categoryId: "256"},
  {jokeId: 579, jokeText: "remamado estaba!", categoryId: "836"},
];

The only thing I need to do is to delete/remove all the objects with categoryId = 256, mutating the jokes array. I've tried to chain a filter with a splice method (ES6 approach), but I could not do it.


Solution

  • let jokes =
    [
    {jokeId: 255, jokeText: "había un borrachín en un boliche", categoryId: "284"},
    {jokeId: 243, jokeText: "había una borrachín en un boliche", categoryId: "284"},
    {jokeId: 554, jokeText: "había otro borrachín en un boliche", categoryId: "284"},
    {jokeId: 424, jokeText: "jodido loco el tipo", categoryId: "256"},
    {jokeId: 257, jokeText: "había un loco en el manicomio", categoryId: "256"},
    {jokeId: 579, jokeText: "remamado estaba!", categoryId: "836"},
    ];
    const filtredJokes = jokes.filter(joke => joke.categoryId !== '256')
    console.log(filtredJokes )