I am trying to delete the 2nd to last item in my array. Using delete puts my indexing out of order?
Getting this using delete myArr[15];
I am trying to delete the 2nd to last item in my array. Using delete puts my indexing out of order?
Getting this using delete myArr[15];
You can use splice
method instead. This is an example:
let arr = [1,2,3];
arr.splice(-2,1);
console.log(arr);
Delete is a method of an Object and it would delete a key(and so the value) of an Object. In an Array, the key would be the index.
An easy way to do this for Array would be something like:
myArr.splice(myArr.length - 2, 1);
Or better:
myArr = [...myArr.slice(0, - 2), ...myArr.slice(-1)]
If you need to delete from the second value onwards in an array, isn't it better for you to create a new array with only the first value?
Here is an example:
let anArray = [
'oneValue',
'twoValue',
'threeValue',
'ecc'
];
console.log('anArray', anArray);
let aNewArray = [anArray[0]];
console.log('aNewArray', aNewArray);