diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec41..5f96fa4bf 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,19 +1,43 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} +function maxOfTwoNumbers(n1, n2) { + if (n1 > n2){ + return n1 + }else{ + return n2 + } +} // Iteration #2: Find longest word const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; -function findLongestWord() {} +function findLongestWord(words) { + longestWord = "" + if (words.length == 0){ + return null + } + for(let i = 0; i < words.length; i++){ + if (words[i].length > longestWord.length){ + longestWord = words[i] + } + } + return longestWord + +} // Iteration #3: Calculate the sum const numbers = [6, 12, 1, 18, 13, 16, 2, 1, 8, 10]; -function sumNumbers() {} +function sumNumbers(numbers) { + let sum = 0; + for(let i = 0; i < numbers.length; i++){ + sum += numbers[i] + } + return sum +} @@ -26,13 +50,26 @@ function sum() {} // Level 1: Array of numbers const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9]; -function averageNumbers() {} +function averageNumbers(numbersAvg) { + if (numbersAvg.length == 0){ + return null + } + let sum = sumNumbers(numbersAvg) + return sum / numbersAvg.length + +} // Level 2: Array of strings const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace']; -function averageWordLength() { } +function averageWordLength(wordsArr) { + let numbersAvg = []; + for(let i = 0; i < wordsArr.length; i++){ + numbersAvg.push(wordsArr[i].length) + } + return averageNumbers(numbersAvg) +} // Bonus - Iteration #4.1 function avg() {} @@ -52,14 +89,33 @@ const wordsUnique = [ 'bring' ]; -function uniquifyArray() {} +function uniquifyArray(wordsUnique) { + + if (wordsUnique.length == 0){ + return null + } + let returnArray = [] + for(let i = 0; i < wordsUnique.length; i++){ + if (!returnArray.includes(wordsUnique[i])){ + returnArray.push(wordsUnique[i]) + } + } + return returnArray + +} // Iteration #6: Find elements const wordsFind = ['machine', 'subset', 'trouble', 'starting', 'matter', 'eating', 'truth', 'disobedience']; -function doesWordExist() {} +function doesWordExist(wordsFind, searchword) { + if (wordsFind.length == 0){ + return null + } + return wordsFind.includes(searchword) + +} @@ -78,7 +134,15 @@ const wordsCount = [ 'matter' ]; -function howManyTimes() {} +function howManyTimes(wordsCount, searchword) { + let counter = 0 + for(let i = 0; i < wordsCount.length; i++){ + if (wordsCount[i] == searchword){ + counter++; + } + } + return counter; +}