Search code examples
javascriptarrayssvelte

How to update an array after splice in Svelte?


I'm learning Svelte, and read in the documentation that arrays need to be reassigned in order for a component or page to update it. For that they devised a more idiomatic solution. Instead of writing:

messages.push('hello');
messages = messages;

you can write instead:

messages = [...messages, 'hello'];

Alright, makes sense. But then the documentation says:

You can use similar patterns to replace pop, shift, unshift and splice.

But how? I cannot see how you can remove items from an array. More to the point, how could I write the following more idiomatically?

messages.splice(messages.indexOf('hello'), 1);
messages = messages;

Solution

  • You could e.g. use the filter array method to create a new array without the element 'hello':

    messages = messages.filter(m => m !== 'hello');