Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to duplicate the last element of an array? [duplicate]

I have an array of objects with length n and I want to extend it to the length n+1. For ease of use I would like to duplicate the last element and then change the properties of the duplicate.

let arr = [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}];

arr.push(arr[1]);       // extend by copying the last
arr[2].id += 1;         // change the id of the new last
arr[2].name = 'foobar'; // change the name of the new last

console.log(arr);

In the snippet above (use the browser console as snippet console is behaving kinda weird here) is what I've tried but for some reason any change to the copied/new last element is also applied to the original/old last/new second-last element in the array.

How can I properly do this and why does my code behave in the way it does?

like image 910
leonheess Avatar asked Jul 29 '19 13:07

leonheess


People also ask

How do you find duplicate values in an array?

function checkIfArrayIsUnique(myArray) { for (var i = 0; i < myArray. length; i++) { for (var j = 0; j < myArray. length; j++) { if (i != j) { if (myArray[i] == myArray[j]) { return true; // means there are duplicate values } } } } return false; // means there are no duplicate values. }

How do I find the second last element of an array?

To get the second to last element in an array, call the at() method on the array, passing it -2 as a parameter, e.g. arr.at(-2) . The at method returns the array element at the specified index.


Video Answer


2 Answers

You could push a copy of the object and omit the same object reference.

let arr = [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}];

arr.push({ ...arr[1] }); // extend by copying the last
arr[2].id += 1;          // change the id of the new last
arr[2].name = 'foobar';  // change the name of the new last

console.log(arr);
like image 84
Nina Scholz Avatar answered Oct 24 '22 02:10

Nina Scholz


const arr = [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}];
const lastEl = Object.assign({}, arr[1]);
lastEl.id = 4;
lastEl.name = 'foo';
arr.push(lastEl);
console.log(arr);
like image 1
Nicolae Maties Avatar answered Oct 24 '22 03:10

Nicolae Maties