diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec41..5784cb19d 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,24 +1,55 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} +function maxOfTwoNumbers(num1, num2) { + if (num1>num2) { + return num1; + } else if (num1 { + if (word.length > longestWord.length) { + longestWord = word; + } + }); + console.log(longestWord); + 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; + numbers.forEach(number => sum += number); + return sum; +} // Iteration #3.1 Bonus: -function sum() {} +function sum(mixedArr) { + let sum = 0; + mixedArr.forEach(el => { + if (typeof el === 'number' || typeof el === 'boolean') { + sum += el; + } else if (typeof el === 'string') { + sum += el.length; + } else { + throw new Error("Unsupported data type"); + } + }); + return sum; +} @@ -26,13 +57,23 @@ 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; + sum = sumNumbers(numbersAvg); + console.log(sum/numbersAvg.length); + 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) { + if (wordsArr.length === 0) return null; + let sum = 0; + wordsArr.forEach(word => sum += word.length); + return sum/wordsArr.length; +} // Bonus - Iteration #4.1 function avg() {} @@ -52,14 +93,27 @@ const wordsUnique = [ 'bring' ]; -function uniquifyArray() {} +function uniquifyArray(words) { + if (words.length === 0) return null; + let uniqueWords = []; + words.forEach(word => { + if(!uniqueWords.includes(word)) { + uniqueWords.push(word) + } + }) + console.log(uniqueWords); + return uniqueWords; +} // Iteration #6: Find elements const wordsFind = ['machine', 'subset', 'trouble', 'starting', 'matter', 'eating', 'truth', 'disobedience']; -function doesWordExist() {} +function doesWordExist(wordsFind, wordToSearch) { + if (wordsFind.length === 0) return null; + return wordsFind.includes(wordToSearch); +} @@ -78,7 +132,11 @@ const wordsCount = [ 'matter' ]; -function howManyTimes() {} +function howManyTimes(wordsCount, wordToSearch) { + let count = 0; + wordsCount.forEach(word => word === wordToSearch ? count++ : ''); + return count; +}