9

I have an javscript object

finalTitleList =[{"Title":"ffd","Iscompleted":"","Id":0},
                 {"Title":"fdfmdbk","Iscompleted":"","Id":1},
                 {"Title":"fdf,d","Iscompleted":"","Id":2}]

Suppose i like to delete an 2nd item using delete finalTitleList[1], after deletion it delete the item but length is not updated(snapshot attached: contain only 2 item but showing length 3).

So when i am adding that object in localstorage using

localStorage.setItem("TaskTitleList16", JSON.stringify(finalTitleList));

On place of deleteditem it shows null.

I want to completely remove that item, please help me.

dev.doc
  • 569
  • 3
  • 12
  • 18
Sahil Gupta
  • 211
  • 3
  • 9
  • Note that *length* isn't affected because *delete* just deletes the member, it doesn't adjust the length of the array. Only array methods (*push*, *pop*, *splice*, etc.) will do that automatically. – RobG Jan 18 '15 at 03:10

1 Answers1

11

You're wanting Array.prototype.splice().

This is an example of usage:

var a = [1, 2, 3, 4, 5]; 
a.splice(2,1); // Being splice at element 2, deleting (and returning) 1 element
console.log(a); // outputs [1, 2, 4, 5]

Delete works a little differently than you may expect with arrays, and shouldn't really be used. For one, delete doesn't affect the length of the array. For two, it leaves this undefined value in the middle of the array, which means you'll have to deal with it in code using the array.

In summary, don't use delete on arrays. There's a ton of built-in methods that you can use to work with arrays, or compose together into your own operations. Use them.

jdphenix
  • 15,022
  • 3
  • 41
  • 74
  • Spot on, jdphenix; you might want to expand this answer to explain why (deleting a numeric index from an array is equivalent to setting that index to `undefined`, it does not shrink the array). – Ethan Brown Jan 18 '15 at 03:08
  • Good one. There is one handy method by John Resig, which you may want to add to your answer. http://ejohn.org/blog/javascript-array-remove/ – naveen Jan 18 '15 at 03:16
  • @naveen OP didn't mention a need for removing an arbitrary number of elements, but feel free to edit it in if you think it's useful information – jdphenix Jan 18 '15 at 03:30
  • How do we get the position of current element in array ? – Santosh Mar 27 '19 at 05:02
  • This is exactly what I needed! Thanks for the explanation @jdphenix! Cheers man =] – Rohjay Jan 11 '21 at 20:16