/ Published in: JavaScript

Adds a method to the Array object that lets you slice the array down to everything before the given value.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * Author: Andrew Hedges, [email protected] * License: free to use, alter, and redistribute without attribution */ /** * Delete the value passed in and any values after it from the array */ Array.prototype.sliceTo = function (val) { var len; len = this.length; while (len > -1) { if (val === this[len]) { this.length = len; break; } --len; } }; // END: Array.prototype.sliceTo // trust, but verify! var a = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']; var b = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']; var c = ['zero', 'one', 'two', 'three', 'four', 'five', 'six']; var d = []; console.log('begin: a'); console.log(a); a.sliceTo('three'); console.log(a); console.log('end: a'); console.log('begin: b'); console.log(b); b.sliceTo('zero'); console.log(b); console.log('end: b'); console.log('begin: c'); console.log(c); c.sliceTo('eleventeen'); console.log(c); console.log('end: c'); console.log('begin: d'); console.log(d); d.sliceTo('three'); console.log(d); console.log('end: d');
Comments
