-1

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];

enter image description here

user992731
  • 3,400
  • 9
  • 53
  • 83
  • 1
    Describe your question with proper example. – Sajeeb Ahamed May 02 '20 at 20:32
  • You could copy the last element's value to the second last, and then delete the last element in the array – GTBebbo May 02 '20 at 20:33
  • I am not sure what you mean. How do you mean delete it but not put the array out of order? Also, you usually use the "splice" directive for deleting something in array in JavaScript. I didn't even know JavaScript had "delete" keyword. – FlatAssembler May 02 '20 at 20:34

3 Answers3

2

You can use splice method instead. This is an example:

let arr = [1,2,3];
arr.splice(-2,1);
console.log(arr);
Majed Badawi
  • 27,616
  • 4
  • 25
  • 48
1

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)]
Ashish Ranjan
  • 12,760
  • 5
  • 27
  • 51
0

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);
Sandman
  • 1,480
  • 7
  • 23