Skip to content

Commit 802a94e

Browse files
committed
Iteration 5 : Unique arrays
1 parent b7e564a commit 802a94e

File tree

1 file changed

+60
-10
lines changed

1 file changed

+60
-10
lines changed

src/functions-and-arrays.js

Lines changed: 60 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -16,33 +16,75 @@ function maxOfTwoNumbers(number1, number2) {
1616
// Iteration #2: Find longest word
1717
const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot'];
1818

19-
function findLongestWord() {}
20-
19+
function findLongestWord(arr) {
20+
if(!arr) return;
21+
let lengths = words.map(word => word.length);
22+
return Math.max(...lengths);
23+
}
24+
findLongestWord(words);
2125

2226

2327
// Iteration #3: Calculate the sum
2428
const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10];
2529

26-
function sumNumbers() {}
27-
30+
function sumNumbers(arr) {
31+
if(!arr) return 0;
32+
let sum=0;
33+
for(let i = 0; i < arr.length; i++) {
34+
sum = sum+arr[i];
35+
}
36+
return sum;
37+
}
38+
sumNumbers(numbers);
2839

2940

3041
// Iteration #3.1 Bonus:
31-
function sum() {}
42+
const mixedArr = [6, 12, 'miami', 1, true, 'barca', '200', 'lisboa', 8, 10];
43+
44+
// should return: 57
45+
function sum(str) {
46+
47+
48+
let sumOfAString = 0;
49+
let addAString = str.split(' ');
50+
for(let i = 0; i < str.length; i++) {
51+
sumOfAString = sumOfAString + str[i];
52+
}
53+
return sumOfAString;
54+
}
55+
sum(mixedArr);
56+
3257

3358

3459

3560
// Iteration #4: Calculate the average
3661
// Level 1: Array of numbers
3762
const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9];
3863

39-
function averageNumbers() {}
40-
64+
function averageNumbers(array) {
65+
if (!array.length) return;
66+
67+
for (let summ = 0, i = 0; i < array.length; i++) {
68+
summ += array[i];
69+
}
70+
return summ / array.length;
71+
}
72+
averageNumbers(numbersAvg);
4173

4274
// Level 2: Array of strings
4375
const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace'];
4476

45-
function averageWordLength() { }
77+
function averageWordLength(arr) {
78+
for(let wordsInArr of arr) {
79+
let lengthArr = wordsInArr.length;
80+
let sUmOfEachWord = 0;
81+
sUmOfEachWord += arr[i];
82+
let avgWLength = sUmOfEachWord / lengthArr;
83+
return avgWLength;
84+
85+
}
86+
}
87+
averageWordLength(wordsArr);
4688

4789
// Bonus - Iteration #4.1
4890
function avg() {}
@@ -62,8 +104,16 @@ const wordsUnique = [
62104
'bring'
63105
];
64106

65-
function uniquifyArray() {}
66-
107+
function uniquifyArray(arr) {
108+
let removedDuplicates = [];
109+
for(let i= 0; i < arr.length; i++) {
110+
if(removedDuplicates.indexOf(arr[i]) === -1) {
111+
removedDuplicates.push(arr[i]);
112+
}
113+
}
114+
return removedDuplicates;
115+
}
116+
uniquifyArray(wordsUnique);
67117

68118

69119
// Iteration #6: Find elements

0 commit comments

Comments
 (0)