diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec41..01384f816 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,19 +1,50 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} - +function maxOfTwoNumbers(NumOne, NumTwo) { + if (NumOne > NumTwo) { + return NumOne; + } else { return NumTwo; + } +} + + // Iteration #2: Find longest word const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; -function findLongestWord() {} +function findLongestWord(words) { + if (words.length === 0){ + return null; + } + let longestWord = words [0] + + for(let i = 1; 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) { + if (numbers.length === 0){ + return 0; + } + let sum = 0; + + for (let i = 0; i < numbers.length; i++) { + sum += numbers [i]; + } + return sum; +} + + @@ -26,13 +57,34 @@ function sum() {} // Level 1: Array of numbers const numbersAvg = [2, 6, 9, 10, 7, 4, 1, 9]; -function averageNumbers() {} +function averageNumbers(numbers) { + if (numbers.length === 0) { + return null; + } + const sum = numbers.reduce ((acc, num) => + acc + num, 0); + const average = sum / numbers.length; + + return average; +} + // Level 2: Array of strings const wordsArr = ['seat', 'correspond', 'linen', 'motif', 'hole', 'smell', 'smart', 'chaos', 'fuel', 'palace']; -function averageWordLength() { } +function averageWordLength(words) { + if (words.length === 0) { + return null; + } + const totalLength = words.reduce((acc,word) => acc + word.length, 0); + const averageLength = totalLength / + words.length; + + return averageLength; +} + + // Bonus - Iteration #4.1 function avg() {} @@ -52,14 +104,39 @@ const wordsUnique = [ 'bring' ]; -function uniquifyArray() {} +function uniquifyArray(array) { + if ( array.length === 0) { + return null; + } + const uniqueArray = []; + array.forEach((element) => { + if (uniqueArray.indexOf(element) === -1) + { + uniqueArray.push(element); + } + }); + + return uniqueArray; +} // Iteration #6: Find elements const wordsFind = ['machine', 'subset', 'trouble', 'starting', 'matter', 'eating', 'truth', 'disobedience']; -function doesWordExist() {} +function doesWordExist(wordArray, + targetWord) { + if (wordArray.length === 0) { + return null; + } + for (let i = 0; i < wordArray.length; i++) + { + if (wordArray[i] === targetWord) { + return true; + } + } + return false; + } @@ -78,7 +155,19 @@ const wordsCount = [ 'matter' ]; -function howManyTimes() {} +function howManyTimes(wordArray, targetWord) { + if (wordArray.length === 0) { + return 0; + } + let count = 0; + for (let i = 0; i < wordArray.length; i++) + { + if(wordArray[i] === targetWord) { + count++; + } + } + return count; +}