Dave Perrett

Useful JScript Array Functions

javascript, programming, web

A couple of useful array manipulation functions: clear, inArray and remove. Courtesy of Todd Ditchendorf

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
/**
 *   Array convenience method to clear membership.
 *
 *   @param object element
 *   @returns void
 */
Array.prototype.clear = function () {
    this.length = 0;
};


/*
 * Return true if the given object is in the array
 *
 *   @param object element
 *   @returns boolean
 */
Array.prototype.inArray = function (obj) {
  var i;
  for (i=0; i < this.length; i++) {
    if (this[i] === obj) {
      return true;
    }
  }
  return false;
};

/**
 *   Array convenience method to remove element.
 *
 *   @param object element
 *   @returns boolean
 */
Array.prototype.remove = function (element) {
  var result = false;
  var array = [];
  for (var i = 0; i < this.length; i++) {
    if (this[i] == element) {
      result = true;
    } else {
      array.push(this[i]);
    }
  }
  this.clear();
  for (var i = 0; i < array.length; i++) {
    this.push(array[i]);
  }
  array = null;
  return result;
};