diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec..93ec3ce 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,20 +1,47 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} +function maxOfTwoNumbers(x,y) { + if (x > y) { + return x; + } + if (y > x){ + return y; + } + else{ + console.log("Both are equal"); + return x; + } +} // Iteration #2: Find longest word const words = ['mystery', 'brother', 'aviator', 'crocodile', 'pearl', 'orchard', 'crackpot']; -function findLongestWord() {} - +function findLongestWord(x) { + let max = x[0]; + if (x.length === 0) return null; + for (let i = 1; i < x.length; i++){ + if (x[i].length > max.length){ + max = x[i]; + } + } + return max; +} +console.log(findLongestWord(words)); // 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 = sum + numbers[i]; + } + return sum; +} +console.log(sumNumbers(numbers)); // Iteration #3.1 Bonus: @@ -26,13 +53,27 @@ 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;} + let average = 0; + let sum = sumNumbers(numbers); + 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(arr) { + if (arr.length === 0) return null; + let sum = 0; + for (let i =0; i< arr.length; i++){ + sum = sum + arr[i].length; + } + return sum/ arr.length; +} // Bonus - Iteration #4.1 function avg() {} @@ -52,15 +93,32 @@ const wordsUnique = [ 'bring' ]; -function uniquifyArray() {} +function uniquifyArray(words) { + if (words.length === 0) return null; + let newArray = []; + for (let i = 0; i < words.length; i++) { + if (words.indexOf(words[i]) === i) { + newArray.push(words[i]); + } + } + return newArray; +} // Iteration #6: Find elements const wordsFind = ['machine', 'subset', 'trouble', 'starting', 'matter', 'eating', 'truth', 'disobedience']; -function doesWordExist() {} - +function doesWordExist(words, word) { + if (words.length === 0) + {return null} + for (let i =0; i< words.length; i++){ + if (words[i] === word){ + return true; + } + } + return false; +} // Iteration #7: Count repetition @@ -78,7 +136,16 @@ const wordsCount = [ 'matter' ]; -function howManyTimes() {} +function howManyTimes(words, word) { + if (words.length === 0) return 0; + let count = 0; + for (let i = 0; i< words.length; i++){ + if (words[i] === word){ + count = count + 1; + } + } + return count; +}