-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

3
  • 1
    Describe your question with proper example. Commented May 2, 2020 at 20:32
  • You could copy the last element's value to the second last, and then delete the last element in the array Commented May 2, 2020 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. Commented May 2, 2020 at 20:34

3 Answers 3

2

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

let arr = [1,2,3]; arr.splice(-2,1); console.log(arr);

Sign up to request clarification or add additional context in comments.

Comments

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

Comments

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.