I've got an array:
var todo = [{item: name}]
What I need to do is pop()
(or is it shift?) the last item off the array, returning an empty array []
.
The issue is, when calling pop()
, it mutates the array in place, rather than returning a new copy. How do I return a copy?
For context, I'm using React and I have a list of things, and it's like a todo list, with buttons for "add another" and "remove", and I need to update the state indirectly.
todo.slice(0, -1)
Just slice the last element away.
You can call slice()
to create a new copy and then mutate the new array
var todo = [
{item: "itemName1"},
{item: "itemName2"}
];
var newTodo = todo.slice().pop();
console.log(newTodo);
console.log(todo);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With