Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript immutable pop()?

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.

like image 849
cjm2671 Avatar asked Feb 22 '19 08:02

cjm2671


2 Answers

 todo.slice(0, -1)

Just slice the last element away.

like image 55
Jonas Wilms Avatar answered Oct 06 '22 01:10

Jonas Wilms


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);
like image 32
kapantzak Avatar answered Oct 06 '22 00:10

kapantzak