· 7 years ago · Nov 22, 2018, 06:52 AM
1/*
2 * When you delete an array element using the delete
3 * operator, the array length is not affected. For example
4 * if you delete arr[2], arr[3] is still arr[3] and arr[2]
5 * is undefined.
6 */
7
8arr = ['a', 'b', 'c', 'd']
9// ["a", "b", "c", "d"]
10delete arr[2]
11// true
12arr
13// ["a", "b", undefined, "d"]
14
15
16/*
17 * One technique for removing content is to use the splice
18 * method to rebuild the array (adding new elements while
19 * removing old elements).
20 */
21
22arr = ['a', 'b', 'c', 'd']
23// ["a", "b", "c", "d"]
24arr.splice(2, 1)
25// ["c"]
26arr
27// ["a", "b", "d"]
28
29
30/*
31 * Another technique John Resig came up with extends the
32 * native prototype for the Array constructor by adding a
33 * remove method.
34 */
35
36Array.prototype.remove = function(from, to) {
37 var rest = this.slice((to || from) + 1 || this.length);
38 this.length = from < 0 ? this.length + from : from;
39 return this.push.apply(this, rest);
40};
41
42// Remove the second item from the array
43arr = ['a', 'b', 'c', 'd']
44// arr = ['a', 'b', 'c', 'd']
45arr.remove(2);
46// 3
47arr
48// ["a", "b", "d"]
49
50// Remove the second-to-last item from the array
51arr = ['a', 'b', 'c', 'd']
52// arr = ['a', 'b', 'c', 'd']
53arr.remove(-2);
54// 3
55arr
56// ["a", "b", "d"]
57
58// Remove the second and third items from the array
59arr = ['a', 'b', 'c', 'd']
60// arr = ['a', 'b', 'c', 'd']
61arr.remove(1,2);
62// 2
63arr
64// ["a", "d"]
65
66// Remove the last and second-to-last items from the array
67arr = ['a', 'b', 'c', 'd']
68// arr = ['a', 'b', 'c', 'd']
69arr.remove(-2,-1);
70// 2
71arr
72// ["a", "b"]
73
74
75/*
76 * And finally, a jQuery technique that uses the grep method
77 * and removes an array item based on it's string value instead
78 * of index
79 */
80
81arr = ['a', 'b', 'c', 'd']
82// ["a", "b", "c", "d"]
83arr = $.grep(arr, function(value) { return value != 'c'; });
84// ["a", "b", "d"]