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?
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. }
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.
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);
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);
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