-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathArray_methods2.txt
193 lines (142 loc) · 5.3 KB
/
Array_methods2.txt
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
// filter() and find() with eg, and Uses
//Array.prototype.filter()
method creates a shallow copy of a portion of a given array, filtered down to just the elements
from the given array that pass the test implemented by the provided function.
method is a copying method, does not mutate the array, but create a new array, hence more convenient to preserve the
original array.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result);
// expected output: Array ["exuberant", "destruction", "present"]
// Syntax similar to Every(), we can say that filter is next step forward to the every()
as it also contain those elements only which passes the callback function.
-----------------------------
Examples
\\ Filtering out all small values
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
// filtered is [12, 130, 44]
-----------------------------
\\ Find all prime numbers in an array
const array = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
function isPrime(num) {
for (let i = 2; num > i; i++) {
if (num % i === 0) {
return false;
}
}
return num > 1;
}
console.log(array.filter(isPrime)); // [2, 3, 5, 7, 11, 13]
----------------------------------------
Filtering invalid entries from JSON
The following example uses filter() to create a filtered JSON of all elements with non-zero, numeric id.
const arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{},
{ id: null },
{ id: NaN },
{ id: "undefined" },
];
let invalidEntries = 0;
function filterByID(item) {
if (Number.isFinite(item.id) && item.id !== 0) {
return true;
}
invalidEntries++;
return false;
}
const arrByID = arr.filter(filterByID);
console.log("Filtered Array\n", arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
console.log("Number of Invalid Entries = ", invalidEntries);
// Number of Invalid Entries = 5
-
--------------------------------------------------------
Searching in array
const fruits = ["apple", "banana", "grapes", "mango", "orange"];
/**
* Filter array items based on search criteria (query)
*/
function filterItems(arr, query) {
return arr.filter((el) => el.toLowerCase().includes(query.toLowerCase()));
}
console.log(filterItems(fruits, "ap")); // ['apple', 'grapes']
console.log(filterItems(fruits, "an")); // ['banana', 'mango', 'orange']
-----------------------------------------------------------------
// Modifying each word
let words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];
const modifiedWords = words.filter((word, index, arr) => {
arr[index + 1] += " extra";
return word.length < 6;
});
console.log(modifiedWords);
// Notice there are three words below length 6, but since they've been modified one is returned
// ["spray"]
// Appending new words
words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];
const appendedWords = words.filter((word, index, arr) => {
arr.push("new");
return word.length < 6;
});
console.log(appendedWords);
// Only three fits the condition even though the `words` itself now has a lot more words with character length less than 6
// ["spray" ,"limit" ,"elite"]
// Deleting words
words = ["spray", "limit", "exuberant", "destruction", "elite", "present"];
const deleteWords = words.filter((word, index, arr) => {
arr.pop();
return word.length < 6;
});
console.log(deleteWords);
// Notice 'elite' is not even obtained as it's been popped off 'words' before filter can even get there
// ["spray" ,"limit"]
==================================================================================================
// Array.prototype.find()
method returns the first element in the provided array that satisfies the provided testing function
undefined if not found
eg,:
const array1 = [5, 12, 8, 130, 44];
const found = array1.find(element => element > 10);
console.log(found);
// expected output: 12
- If you need the index of the found element in the array, use findIndex().
- If you need to find the index of a value, use indexOf().
- If you need to find if a value exists in an array, use includes().
(both indexOf() and includes() checks each element for equality with the value instead of using a testing function.)
- If you need to find if any element satisfies the provided testing function, use some().
Examples:
Find an object in an array by one of its properties
const inventory = [
{ name: "apples", quantity: 2 },
{ name: "bananas", quantity: 0 },
{ name: "cherries", quantity: 5 },
];
function isCherries(fruit) {
return fruit.name === "cherries";
}
console.log(inventory.find(isCherries));
// { name: 'cherries', quantity: 5 }
//cc Using arrow function and destructuring
const result = inventory.find(({ name }) => name === "cherries");
console.log(result); // { name: 'cherries', quantity: 5 }
-------------------------------
Find a prime number in an array
function isPrime(element, index, array) {
let start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) {
return false;
}
}
return element > 1;
}
console.log([4, 6, 8, 12].find(isPrime)); // undefined, not found
console.log([4, 5, 8, 12].find(isPrime)); // 5