Sunday, 23 April 2017

javascript - Remove value from associative array












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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...