If you are working with Javascript Array, you would probably benefit from these additional functions handling Array elements. They allow to add and remove items without fetching the whole array.
To push an item to the Array (unique item) we are using the following function:
1 2 3 4 5 6 7 |
Array.prototype.pushUniqueItem = function (item) { if (this.indexOf(item) == -1) { this.push(item); return true; } return false; } |
To remove an item to the Array we can use the following function:
1 2 3 4 5 |
Array.prototype.removeItem = function (el) { if (this.indexOf(el) >= 0) { return this.splice(this.indexOf(el), 1); } } |
How to use it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
Array.prototype.pushUniqueItem = function (item) { if (this.indexOf(item) == -1) { this.push(item); return true; } return false; } Array.prototype.removeItem = function (el) { if (this.indexOf(el) >= 0) { return this.splice(this.indexOf(el), 1); } } var a = new Array(1,2,3); a.pushUniqueItem(4); a.removeItem(2); a.removeItem(1); alert(a); |





