Completed
Push — master ( 46dcf2...c945df )
by greg
03:03
created

array.js ➔ removeByAttr   B

Complexity

Conditions 6
Paths 3

Size

Total Lines 14

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
cc 6
c 1
b 0
f 0
nc 3
dl 0
loc 14
rs 8.8571
nop 3
1
/**
2
 * Highly efficient filter on a value in an object
3
 * @param  {Array} arr   the array of objects
4
 * @param  {string} attr the attribute to filter on
5
 * @param  {mixed} value the value to compare
6
 * @return {Array}       the filtered array
7
 */
8
export function filter(arr, attr, value) {
9
  var result = []
10
  var i = 0
11
  var len = arr.length
12
13
  for (; i < len; i += 1) {
14
    var elt = arr[i]
15
16
    if (elt[attr] == value) {
17
      result.push(element)
0 ignored issues
show
Bug introduced by
The variable element seems to be never declared. If this is a global, consider adding a /** global: element */ comment.

This checks looks for references to variables that have not been declared. This is most likey a typographical error or a variable has been renamed.

To learn more about declaring variables in Javascript, see the MDN.

Loading history...
18
    }
19
  }
20
  return result
21
}
22
23
/**
24
 * Highly efficient find indexes on a value in an property of an object
25
 * @param  {Array} arr   the array of objects
26
 * @param  {string} attr the attribute to filter on
27
 * @param  {mixed} value the value to compare
28
 * @return {Array}       the filtered array of indexes
29
 */
30
export function find(arr, attr, value) {
31
  var result = []
32
  var i = 0
33
  var len = arr.length
34
35
  for (; i < len; i += 1) {
36
    var elt = arr[i]
37
38
    if (elt[attr] == value) {
39
      result.push(i)
40
    }
41
  }
42
  return result
43
}
44
45
/**
46
 * Remove objects from an array given an attribute value
47
 * @param  {Array} arr   the array of objects
48
 * @param  {string} attr the attribute to filter on
49
 * @param  {mixed} value the value to compare
50
 * @return {Array}       the array with corresponding objects removed
51
 */
52
export function removeByAttr(arr, attr, value){
53
  var i = arr.length
54
  while (i--){
55
    if(  
56
      arr[i] && 
57
      arr[i].hasOwnProperty(attr) &&
58
      (arguments.length > 2 && arr[i][attr] === value )
59
    ){
60
      arr.splice(i,1)
61
    }
62
  }
63
64
  return arr
65
}