-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy patharray.find.js
More file actions
36 lines (30 loc) · 746 Bytes
/
array.find.js
File metadata and controls
36 lines (30 loc) · 746 Bytes
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
/*
* @title: Find Item in Array
* @description: Simple function to find an item in array
* @author: Thorsten Kober
* @email: [email protected]
*/
function countItems(arr, item) {
let count = 0;
const result = [];
function flattenArray(arr) {
for (let i = 0; i < arr.length; i++) {
Array.isArray(arr[i]) ? flattenArray(arr[i]) : result.push(arr[i]);
}
}
flattenArray(arr);
for (let i = 0; i < result.length; i++) {
if (result[i].indexOf(item) !== -1) {
count++;
}
}
return count;
}
// npx jest algorithms/array/array.find.js
test('count items in array', () => {
const arr = [
'apple',
['banana', 'strawberry', 'apple'],
];
expect(countItems(arr, 'apple')).toEqual(2);
});