I am having an array, from which I want to remove a value.
Consider this as an array
[ 'utils': [ 'util1', 'util2' ] ]
Now I just want to remove util2
. How can I do that, I tried using delete
but it didn't work.
Can anyone help me?
Answer
Use the splice
method:
var object = { 'utils': [ 'util1', 'util2' ] }
object.utils.splice(1, 1);
If you don't know the actual position of the array element, you'd need to iterate over the array and splice the element from there. Try the following method:
for (var i = object.utils.length; i--;) {
var index = object.utils.indexOf('util2');
if (index === -1) break;
if (i === index) {
object.utils.splice(i, 1); break;
}
}
Update: techfoobar's answer seems to be more idiomatic than mine. Consider using his instead.
No comments:
Post a Comment