-
Notifications
You must be signed in to change notification settings - Fork 47
Expand file tree
/
Copy patharray.js
More file actions
113 lines (101 loc) · 2.4 KB
/
array.js
File metadata and controls
113 lines (101 loc) · 2.4 KB
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
/**
* Returns an index of the specified element in array or -1 if element is not found
*
* @param {array} arr
* @param {any} value
* @return {number}
*
* @example
* ['Ace', 10, true], 10 => 1
* ['Array', 'Number', 'string'], 'Date' => -1
* [0, 1, 2, 3, 4, 5], 5 => 5
*/
function findElement(arr, value) {
for (let i = 0; i < arr.length; i++) {
if (arr[i] === value) {
return i;
}
}
return -1;
}
/**
* Returns the doubled array - elements of the specified array are repeated twice
* using original order
*
* @param {array} arr
* @return {array}
*
* @example
* ['Ace', 10, true] => ['Ace', 10, true, 'Ace', 10, true]
* [0, 1, 2, 3, 4, 5] => [0, 1, 2, 3, 4, 5, 0, 1, 2, 3, 4, 5]
* [] => []
*/
function doubleArray(arr) {
return arr.concat(arr);
}
/**
* Returns an array of positive numbers from the specified array in original order
*
* @param {array} arr
* @return {array}
*
* @example
* [ 0, 1, 2, 3, 4, 5 ] => [ 1, 2, 3, 4, 5 ]
* [-1, 2, -5, -4, 0] => [ 2 ]
* [] => []
*/
function getArrayOfPositives(arr) {
return arr.filter(num => num > 0);
}
/**
* Removes falsy values from the specified array
* Falsy values: false, null, 0, "", undefined, and NaN.
* (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description)
*
* @param {array} arr
* @return {array}
*
* @example
* [ 0, false, 'cat', NaN, true, '' ] => [ 'cat', true ]
* [ 1, 2, 3, 4, 5, 'false' ] => [ 1, 2, 3, 4, 5, 'false' ]
* [ false, 0, NaN, '', undefined ] => [ ]
*/
function removeFalsyValues(arr) {
return arr.filter(item => !!item);
}
/**
* Returns the array of string lengths from the specified string array.
*
* @param {array} arr
* @return {array}
*
* @example
* [ '', 'a', 'bc', 'def', 'ghij' ] => [ 0, 1, 2, 3, 4 ]
* [ 'angular', 'react', 'ember' ] => [ 7, 5, 5 ]
*/
function getStringsLength(arr) {
return arr.map(str => str.length);
}
/**
* Returns the sum of all items in the specified array of numbers
*
* @param {array} arr
* @return {number}
*
* @example
* [] => 0
* [ 1, 2, 3 ] => 6
* [ -1, 1, -1, 1 ] => 0
* [ 1, 10, 100, 1000 ] => 1111
*/
function getItemsSum(arr) {
return arr.reduce((sum, num) => sum + num, 0);
}
module.exports = {
findElement,
doubleArray,
getArrayOfPositives,
removeFalsyValues,
getStringsLength,
getItemsSum,
};