diff --git a/src/functions-and-arrays.js b/src/functions-and-arrays.js index 3a7dbec41..03e98e33b 100644 --- a/src/functions-and-arrays.js +++ b/src/functions-and-arrays.js @@ -1,41 +1,134 @@ // Iteration #1: Find the maximum -function maxOfTwoNumbers() {} - - +function maxOfTwoNumbers(num1, num2) { + if (num1>num2) { + return num1; + } else if (num1 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 result = numbers[0]; + for (let i=1; i { + if (typeof element === 'number') { + sum += element; + count += 1; + } else if (typeof element === 'boolean') { + sum += element ? 1 : 0; + count += 1; + } else if (typeof element === 'string') { + sum += element.length; + count += 1; + } + + }); + + const average = count === 0 ? 0 : sum / count; + return average; +} + + + // Iteration #5: Unique arrays const wordsUnique = [ @@ -52,14 +145,31 @@ const wordsUnique = [ 'bring' ]; -function uniquifyArray() {} +function uniquifyArray(words) { + if (words.length === 0) { + return null; + } + + const uniqueArray = []; + words.forEach(word => { + if (!uniqueArray.includes(word)) { + uniqueArray.push(word); + } + }); + return uniqueArray; +} // Iteration #6: Find elements const wordsFind = ['machine', 'subset', 'trouble', 'starting', 'matter', 'eating', 'truth', 'disobedience']; -function doesWordExist() {} +function doesWordExist(array, word) { + if (array.length === 0) { + return null; + } + return array.includes(word); +} @@ -78,9 +188,15 @@ const wordsCount = [ 'matter' ]; -function howManyTimes() {} - - +function howManyTimes(array, word) { + let count = 0; + for (let i = 0; i < array.length; i++) { + if (array[i] === word) { + count++; + } + } + return count; +} // Iteration #8: Bonus const matrix = [