-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfilter.js
86 lines (71 loc) · 2.18 KB
/
filter.js
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
/**
* The filter() method creates a new array with all elements that pass the test implemented by the provided function.
*/
var words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
/**
* var newArray = arr.filter(callback[, thisArg])
* callback is invoked with three arguments:
* 1. the value of the element
* 2. the index of the element
* 3. the Array object being traversed
*
* array.filter(function(currentValue, index, arr), thisValue)
*/
const result = words.filter(word => word.length > 6);
console.log(result);
/**
* @output
* [ 'exuberant', 'destruction', 'present' ]
*/
///////////////////// Filtering out all small values //////////////////////
function isBigEnough(value) {
return value >= 10;
}
var filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// same as above
// var filtered = [12, 5, 8, 130, 44].filter(arr => arr >= 10);
console.log(filtered);
/**
* @output
* [12, 130, 44]
*/
/////////// searching in array ///////////////
var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];
/**
* Array filters items based on search criteria (query)
*/
function filterItems(query) {
return fruits.filter(value => value.toLowerCase().indexOf(query.toLowerCase()) > -1)
}
console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']
/////////////// Filtering invalid entries from JSON ////////////////////
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{ },
{ id: null },
{ id: NaN },
{ id: 'undefined' }
];
var invalidCount = 0;
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}
function filterById(value){
if(isNumber(value.id) && value.id !== 0){
return true;
}else{
invalidCount++;
return false;
}
};
var arrResult = arr.filter(filterById);
console.log(arrResult) // [ { id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 } ]
/////////////////// filter even number ////////////////////////////////
var arrList = [1,2,3,4,5,6,7,8,9,10];
var arrListNew = arrList.filter(element => element%2 == 0);
console.log(arrListNew);