Posted By


segdeha on 06/13/09

Tagged


Statistics


Viewed 515 times
Favorited by 0 user(s)

Array.prototype.sliceTo


/ Published in: JavaScript
Save to your folder(s)

Adds a method to the Array object that lets you slice the array down to everything before the given value.


Copy this code and paste it in your HTML
  1. /**
  2.  * Author: Andrew Hedges, [email protected]
  3.  * License: free to use, alter, and redistribute without attribution
  4.  */
  5.  
  6. /**
  7.  * Delete the value passed in and any values after it from the array
  8.  */
  9. Array.prototype.sliceTo = function (val) {
  10. var len;
  11. len = this.length;
  12. while (len > -1) {
  13. if (val === this[len]) {
  14. this.length = len;
  15. break;
  16. }
  17. --len;
  18. }
  19. };
  20. // END: Array.prototype.sliceTo
  21.  
  22. // trust, but verify!
  23. var a = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
  24. var b = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
  25. var c = ['zero', 'one', 'two', 'three', 'four', 'five', 'six'];
  26. var d = [];
  27.  
  28. console.log('begin: a');
  29. console.log(a);
  30. a.sliceTo('three');
  31. console.log(a);
  32. console.log('end: a');
  33.  
  34. console.log('begin: b');
  35. console.log(b);
  36. b.sliceTo('zero');
  37. console.log(b);
  38. console.log('end: b');
  39.  
  40. console.log('begin: c');
  41. console.log(c);
  42. c.sliceTo('eleventeen');
  43. console.log(c);
  44. console.log('end: c');
  45.  
  46. console.log('begin: d');
  47. console.log(d);
  48. d.sliceTo('three');
  49. console.log(d);
  50. console.log('end: d');

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.