Skip to content

Instantly share code, notes, and snippets.

@kanglicheng
Last active September 21, 2023 18:34
Show Gist options
  • Save kanglicheng/f703510aa10fdd81eaa644c710dba095 to your computer and use it in GitHub Desktop.
Save kanglicheng/f703510aa10fdd81eaa644c710dba095 to your computer and use it in GitHub Desktop.
// #52
function getLengthOfThreeWords(word1, word2, word3) {
return word1.length+ word2.length+word3.length
}
//#53
/*
Write a function called "joinArrays".
Given two arrays, "joinArrays" returns an array with the elements of "arr1" in order,
followed by the elementsin "arr2".
var output = joinArrays([1, 2], [3, 4]);
console.log(output); // --> [1, 2, 3, 4]
You should be familiar with the "concat" method for this problem.
*/
function joinArrays(arr1, arr2) {
return arr1.concat(arr2)
}
// #54
/*
Write a function called "getElementsAfter".
Given an array and an index, "getElementsAfter" returns a new array with all
the elements after (but not including) the given index.
var output = getElementsAfter(['a', 'b', 'c', 'd', 'e'], 2);
console.log(output); // --> ['d', 'e']
*/
function getElementsAfter(array, n) {
return array.slice(n+1)
}
// #63
/*
Write a function called "getAllWords".
Given a sentence, "getAllWords" returns an array containing every word in the sentence.
Notes:
* If given an empty string, it should return an empty array.
var output = getAllWords('Radagast the Brown');
console.log(output); // --> ['Radagast', 'the', 'Brown']
*/
function getAllWords(str) {
return str.split(" ").(Boolean)
}
// #64
/*
Write a function called "countWords".
Given a string, "countWords" returns an object where each key is a word in the given
string, with its value being how many times that word appeared in th given string.
Notes:
* If given an empty string, it should return an empty object.
var output = countWords('ask a bunch get a bunch');
console.log(output); // --> {ask: 1, a: 2, bunch: 2, get: 1}
*/
function countWords(str) {
var dict = {};
if (str !== "") {
var arr = str.split(" ");
for (var i = 0; i < arr.length; i++) {
if (typeof dict[arr[i]] === "undefined") {
dict[arr[i]] = 1;
} else {
dict[arr[i]] += 1;
}
}
}
return dict;
}
// #65
/*
Write a function called "removeFromBack".
Given an array, "removeFromBack" returns the given array with its last element removed.
Notes:
* You should be familiar with the method 'pop'.
var output = removeFromBack([1, 2, 3]);
console.log(output); // --> [1, 2]
*/
function removeFromBack(arr) {
arr.pop()
return arr }
// #66
/*
Write a function called "or".
Given 2 boolean expressions, "or" returns true or false, corresponding to the || operator.
Notes:
* Do not use the || operator.
* Use ! and && operators instead.
var output = or(true, false);
console.log(output); // --> true;
*/
function or(expression1, expression2) {
if (expression1&&expression2)
{return true }
else if( !expression1 && !expression2) {return false}
else {return true}
}
// #67
/*
Write a function called "isEitherEvenOrAreBoth7".
Given two numbers, 'isEitherEvenOrAreBoth7' returns whether at least one of them is even, or, both of them are 7.
var output = isEitherEvenOrAreBoth7(3, 7);
console.log(output); // --> false
var output = isEitherEvenOrAreBoth7(2, 3);
console.log(output); // --> true
*/
function isEitherEvenOrAreBoth7(num1, num2) {
if (num1 ===7 && num2 ===7) return true
if(num1 %2 ===0 && num2%2===0) return true
else if(num1%2===0 || num2%2===0) return true
else return false
}
// #68
/*
Write a function called "isEitherEvenAndLessThan9".
Given two numbers, 'isEitherEvenAndLessThan9' returns whether at least one of them is even, and, both of them
are less than 9.
var output = isEitherEvenAndLessThan9(2, 4);
console.log(output); // --> true
var output = isEitherEvenAndLessThan9(72, 2);
console.log(output); // --> false
*/
function isEitherEvenAndLessThan9(num1, num2) {
if (num1 > 9 || num2 >9) return false
if (num1 %2 ===0 || num2 %2 === 0 ) return true
else return false
}
// #69
/*
Write a function called "extend".
Given two objects, "extend" adds properties from the 2nd object to the 1st object.
Notes:
* Add any keys that are not in the 1st object.
* If the 1st object already has a given key, ignore it (do not overwrite the property value).
* Do not modify the 2nd object at all.
var obj1 = {
a: 1,
b: 2
};
var obj2 = {
b: 4,
c: 3
};
extend(obj1, obj2);
console.log(obj1); // --> {a: 1, b: 2, c: 3}
console.log(obj2); // --> {b: 4, c: 3}
*/
function extend(obj1, obj2) {
for (var key in obj2) {
if(obj1[key] === undefined){
obj1[key] = obj2[key];
}
}
return obj1;
}
// #70
/*
Write a function called "removeNumbersLargerThan".
Given a number and an object, "removeNumbersLargerThan" removes any properties whose values are numbers greater
than the given number.
var obj = {
a: 8,
b: 2,
c: 'montana'
}
removeNumbersLargerThan(5, obj);
console.log(obj); // --> { b: 2, c: 'montana' }
*/
function removeNumbersLargerThan(num, obj) {
for (x in obj){
if ( typeof(obj[x]) === 'number' && obj[x] > num){
delete obj[x]
}
}
}
// #71
/*
Write a function called "removeNumbersLessThan".
Given a number and an object, "removeNumbersLessThan" removes any properties whose values are numbers less
than the given number.
var obj = {
a: 8,
b: 2,
c: 'montana'
}
removeNumbersLessThan(5, obj);
console.log(obj); // --> { a: 8, c: 'montana' }
*/
function removeNumbersLessThan(num, obj) {
for (x in obj){
if ( typeof(obj[x]) === 'number' && obj[x] < num){
delete obj[x]
}
}
}
// #72
/*
Write a function called "removeStringValuesLongerThan".
Given an number and an object, "removeStringValuesLongerThan" removes any properties on the given object whose values
are strings longer than the given number.
var obj = {
name: 'Montana',
age: 20,
location: 'Texas'
};
removeStringValuesLongerThan(6, obj);
console.log(obj); // { age: 20, location: 'Texas' }
*/
function removeStringValuesLongerThan(num, obj) {
for (x in obj)
{
if ((typeof obj[x] === "string")&& obj[x].length >num)
delete obj[x]
}
}
// #73
/*
Write a function called "removeEvenValues".
Given an object, "removeEvenValues" removes any properties whose values are even numbers.
Do this in place and return the original object, do not construct a cloned object that omits the properties.
Example:
var obj = {
a: 2,
b: 3,
c: 4
};
removeEvenValues(obj);
console.log(obj); // --> { b: 3 }
*/
function removeEvenValues(obj) {
for (var key in obj){
if (obj[key] % 2 === 0){
delete obj[key];
}
}
return obj;
}
// #74
/*
Write a function called "countNumberOfKeys".
Given an object, "countNumberOfKeys" returns how many properties the given object has.
var obj = {
a: 1,
b: 2,
c: 3
};
var output = countNumberOfKeys(obj);
console.log(output); // --> 3
*/
function countNumberOfKeys(obj) {
var count = 0;
for (var key in obj){
key = count++
}
return count;
}
// #75
/*
Write a function called "removeOddValues".
Given an object, "removeOddValues" removes any properties whose valuse are odd numbers.
var obj = {
a: 2,
b: 3,
c: 4
};
removeOddValues(obj);
console.log(obj); // --> { a: 2, c: 4 }
*/
function removeOddValues(obj) {
for (var key in obj)
{
if (obj[key] %2 !=0)
delete obj[key]
}
return obj
}
// #76
/*
Write a function called "removeArrayValues".
Given an object, "removeArrayValues" removes any properties whose values are arrays.
var obj = {
a: [1, 3, 4],
b: 2,
c: ['hi', 'there']
}
removeArrayValues(obj);
console.log(obj); // --> { b: 2 }
*/
function removeArrayValues(obj) {
for (var key in obj)
{
if(Array.isArray(obj[key]))
delete obj[key]
}
return obj
}
// alternative solution to #76, check if constructor is array
function removeArrayValues(obj) {
for (var key in obj)
{
if(obj[key].constructor === Array)
delete obj[key]
}
return obj
}
// #78
/*
Write a function called "removeStringValues".
Given an object, "removeStringValues" removes any properties on the given object whose values are strings.
var obj = {
name: 'Sam',
age: 20
}
removeStringValues(obj);
console.log(obj); // { age: 20 }
*/
function removeStringValues(obj) {
for (var key in obj)
{
if ((typeof obj[key] === "string"))
delete obj[key]
}
}
// #79
/*
Write a function called "convertDoubleSpaceToSingle".
Given a string, "convertDoubleSpaceToSingle" returns the passed in string, with all the double spaces converted
to single spaces.
var output = convertDoubleSpaceToSingle("string with double spaces");
console.log(output); // --> "string with double spaces"
Notes:
* In order to do this problem, you should be familiar with "String.split", and "Array.join".
*/
function convertDoubleSpaceToSingle(str) {
var newArray = str.split(" ");
var newArray2 = [];
for (var i = 0; i < newArray.length; i++){
if (newArray[i] !== ""){
newArray2.push(newArray[i]);
}
}
return newArray2.join(" ");
}
// #80
/*
Write a function called "joinThreeArrays".
Given three arrays, "joinThreeArrays" returns an array with the elements of "arr1" in order followed by the
elements in "arr2" in order followed by the elements of "arr3" in order.
var output = joinThreeArrays([1, 2], [3, 4], [5, 6]);
console.log(output); // --> [1, 2, 3, 4, 5, 6]
You should be familiar with the "concat" method for this problem.
*/
function joinThreeArrays(arr1, arr2, arr3) {
return arr1.concat(arr2).concat(arr3)
}
// #81
/*
Write a function called "addToFrontOfNew".
Given an array and an element, "addToFrontOfNew" returns a new array containing all the elements of the given
array, with the given element added to the front.
Important: It should be a NEW array instance, not the original array instance.
var input = [1, 2];
var output = addToFrontOfNew(input, 3);
console.log(output); // --> [3, 1, 2];
console.log(input); --> [1, 2]
*/
function addToFrontOfNew(arr, element) {
var arrNew=[]
arrNew.push(element)
return arrNew.concat(arr)
}
// #82
/*
Write a function called "addToBackNew".
Given an array and an element, "addToBackNew" returns a clone of the given array, with the given element added to the end.
Important: It should be a NEW array instance, not the original array instance.
var input = [1, 2];
var output = addToBackOfNew(input, 3);
console.log(input); // --> [1, 2]
console.log(output); // --> [1, 2, 3]
*/
function addToBackOfNew(arr, element) {
var newArr= []
var newArr2= newArr.concat(arr)
newArr2.push(element)
return newArr2
}
// #83
/*
Write a function called "getAllElementsButNth".
Given an array and an index, "getAllElementsButNth" returns an array with all the elements but the nth.
var output = getAllElementsButNth(['a', 'b', 'c'], 1);
console.log(output); // --> ['a', 'c']
*/
function getAllElementsButNth(array, n) {
array.splice( n, 1) // at nth index, remove 1 item.
return array
}
// #84
/*
Write a function called "areValidCredentials".
Given a name and a password, "areValidCredentials", returns true if the name is longer than 3 characters,
AND, the password is at least 8 characters long. Otherwise it returns false.
var output = areValidCredentials('Ritu', 'mylongpassword')
console.log(output); // --> true
*/
function areValidCredentials(name, password) {
if(name.length >3 && password.length >=8) return true
else return false
}
// #85
/*
Write a function called "getIndexOf".
Given a character and a string, "getIndexOf" returns the first position of the given character in the given string.
Notes:
* Strings are zero indexed, meaning the first character in a string is at position 0.
* When a string contains more than one occurrence of a character, it should return the index of its first occurrence.
* If the character does not exist in the string, it should return -1.
* Do not use the native indexOf function in your implementation.
var output = getIndexOf('a', 'I am a hacker');
console.log(output); // --> 2
*/
function getIndexOf(char, str){
for (var i = 0; i < str.length; i++){
if (str[i] === char){
return i;
}
}
return -1;
}
// #86
/*
Write a function called "findMinLengthOfThreeWords".
Given 3 words, "findMinLengthOfThreeWords" returns the length of the shortest word.
var output = findMinLengthOfThreeWords('a', 'be', 'see');
console.log(output); // --> 1
*/
function findMinLengthOfThreeWords(word1, word2, word3) {
var result = 100;
var newArray = [word1, word2, word3];
for (var i = 0; i < newArray.length; i++) {
if (newArray[i].length < result){
result = newArray[i].length
}
}
return result;
}
// #87
/*
Write a function called "findMaxLengthOfThreeWords".
Given 3 words, "findMaxLengthOfThreeWords" returns the length of the longest word.
var output = findMaxLengthOfThreeWords('a', 'be', 'see');
console.log(output); // --> 3
*/
function findMaxLengthOfThreeWords(word1, word2, word3) {
return Math.max(word1.length, word2.length, word3.length)
}
// #88
/*
Write a function called "getElementsThatEqual10AtProperty".
Given an object and a key, "getElementsThatEqual10AtProperty" returns
an array containing all the elements of the array located at the given key that are equal to ten.
Notes:
* If the array is empty, it should return an empty array.
* If the array contains no elements are equal to 10, it should return an empty array.
* If the property at the given key is not an array, it should return an empty array.
* If there is no property at the key, it should return an empty array.
var obj = {
key: [1000, 10, 50, 10]
};
var output = getElementsThatEqual10AtProperty(obj, 'key');
console.log(output); // --> [10, 10]
*/
function getElementsThatEqual10AtProperty(obj, key) {
var ans =[]
for (elem in obj[key])
{
if(obj[key][elem] === 10)
ans.push(obj[key][elem])
}
return ans
}
// #89
/*
Write a function called "select".
Given an array and an object, "select" returns a new object whose properties are those in the given object AND whose keys are present in the given array.
Notes:
* If keys are present in the given array, but are not in the given object, it should ignore them.
* It does not modify the passed in object.
var arr = ['a', 'c', 'e'];
var obj = {
a: 1,
b: 2,
c: 3,
d: 4
};
var output = select(arr, obj);
console.log(output); // --> { a: 1, c: 3 }
*/
function select(arr, obj) {
var newObject = {};
for (var key in obj){
for (var i = 0; i < arr.length; i++){
if (arr[i] === key){
newObject[key] = obj[key];
}
}
}
return newObject;
}
// #91
/*
Write a function called "countAllCharacters".
Given a string, "countAllCharacters" returns an object where each key is a character in the given string.
The value of each key should be how many times each character appeared in the given string.
Notes:
* If given an empty string, countAllCharacters should return an empty object.
var output = countAllCharacters('banana');
console.log(output); // --> {b: 1, a: 3, n: 2}
*/
function countAllCharacters(str) {
d={}
if (str ==="") return d
for (var i =0; i<str.length; i++){
if( typeof d[str[i]] === "undefined")
{
d[str[i]]=1
}
else d[str[i]]+=1
}
return d
}
// #92
/*
Write a function called "getElementsGreaterThan10AtProperty".
Given an object and a key, "getElementsGreaterThan10AtProperty" returns
an array containing the elements within the array, located at the given key, that are greater than 10.
Notes:
* If the array is empty, it should return an empty array.
* If the array contains no elements greater than 10, it should return an empty array.
* If the property at the given key is not an array, it should return an empty array.
* If there is no property at the key, it should return an empty array.
var obj = {
key: [1, 20, 30]
};
var output = getElementsGreaterThan10AtProperty(obj, 'key');
console.log(output); // --> [20, 30]
*/
function getElementsGreaterThan10AtProperty(obj, key) {
var arr = [];
for (var x in obj[key]) {
if (obj[key][x] > 10) {
arr.push(obj[key][x]);
}
}
return arr;
}
// #93
/*
Write a function called "removeElement".
Given an array of elements, and a "discarder" parameter, "removeElement" returns an array containing
the items in the given array that do not match the "discarder" parameter.
Notes:
* If all the elements match, it should return an empty array.
* If an empty array is passed in, it should return an empty array.
var output = removeElement([1, 2, 3, 2, 1], 2);
console.log(output); // --> [1, 3, 1]
*/
function removeElement(array, discarder) {
var filteredAry = array.filter(function(e) { return e !== discarder })
return filteredAry;
}
// #94
// #96
function getLastElementOfProperty(obj, key) {
// your code here
if(obj[key] instanceof Array)
return obj[key][obj[key].length-1]
}
// #97
function keep(array, keeper) {
var filteredAry = array.filter(function(e) { return e === keeper })
return filteredAry;
}
// #100
function getAverageOfElementsAtProperty(obj, key) {
if ((typeof obj[key] != "undefined") && Array.isArray(obj[key]) && obj[key].length > 0) {
var sum = 0;
for (var elem in obj[key]) {
sum += obj[key][elem];
}
return sum / obj[key].length;
} else {
return 0;
}
}
// #102
/*
Write a function called "filterOddLengthWords".
Given an array of string, "filterOddLengthWords" returns an array containing only the elements of
the given array whose lengths are odd numbers.
var output = filterOddLengthWords(['there', 'it', 'is', 'now']);
console.log(output); // --> ['there', "now']
*/
function filterOddLengthWords(words) {
var filteredAry = words.filter(function(e) { return e.length % 2 !== 0 })
return filteredAry;
}
// #103
/*
Write a function called "getSquaredElementsAtProperty".
Given an object and a key, "getSquaredElementsAtProperty" returns an array containing all the
squared elements of the array located at the given key.
Notes:
* If the array is empty, it should return an empty array.
* If the property at the given key is not an array, it should return an empty array.
* If there is no property at the key, it should return an empty array.
var obj = {
key: [2, 1, 5]
};
var output = getSquaredElementsAtProperty(obj, 'key');
console.log(output); // --> [4, 1, 25]
*/
function getSquaredElementsAtProperty(obj, key) {
var ans =[]
if ((typeof obj[key] != "undefined") && Array.isArray(obj[key]) && obj[key].length > 0)
{
for (var elem in obj[key])
{
ans.push(Math.pow(obj[key][elem], 2));
}
}
return ans
}
// #103
/*
Write a function called "getOddElementsAtProperty".
Given an object and a key, "getOddElementsAtProperty" returns an array
containing all the odd elements of the array located at the given key.
Notes:
* If the array is empty, it should return an empty array.
* If it contains no odd elements, it should return an empty array.
* If the property at the given key is not an array, it should return an empty array.
* If there is no property at the key, it should return an empty array.
var obj = {
key: [1, 2, 3, 4, 5]
};
var output = getOddElementsAtProperty(obj, 'key');
console.log(output); // --> [1, 3, 5]
*/
function getOddElementsAtProperty(obj, key) {
var ans =[]
if ((typeof obj[key] != "undefined") && Array.isArray(obj[key]) && obj[key].length > 0){
for (var elem in obj[key])
{
if(obj[key][elem] %2 != 0)
ans.push(obj[key][elem])
}
}
return ans
}
// #105
/*
Write a function called "getEvenElementsAtProperty".
Given an object and a key, "getEvenElementsAtProperty" returns an array containing all
the even elements of the array located at the given key.
Notes:
* If the array is empty, it should return an empty array.
* If the array contains no even elements, it should return an empty array.
* If the property at the given key is not an array, it should return an empty array.
* If there is no property at the given key, it should return an empty array.
var obj = {
key: [1000, 11, 50, 17]
};
var output = getEvenElementsAtProperty(obj, 'key');
console.log(output); // --> [1000, 50]
*/
function getEvenElementsAtProperty(obj, key) {
var ans =[]
if ((typeof obj[key] != "undefined") && Array.isArray(obj[key]) && obj[key].length > 0){
for (var elem in obj[key])
{
if (obj[key][elem] %2 ===0)
ans.push(obj[key][elem])
}
}
return ans
}
// #106
/*
Write a function called "filterEvenLengthWords".
Given an array of strings, "filterEvenLengthWords" returns an array containing only the elements of the given array
whose length is an even number.
var output = filterEvenLengthWords(['word', 'words', 'word', 'words']);
console.log(output); // --> ['word', 'word']
*/
function filterEvenElements(arr) {
var filteredAry = arr.filter(function(e) { return e % 2 === 0; });
return filteredAry;
}
// #107
/*
Write a function called "getLengthOfLongestElement".
Given an array, "getLengthOfLongestElement" returns the length of the longest string in the given array.
Notes:
* It should return 0 if the array is empty.
var output = getLengthOfLongestElement(['one', 'two', 'three']);
console.log(output); // --> 5
*/
function getLengthOfLongestElement(arr) {
if (arr.length ===0) return 0
var maxLength = arr[0].length
for ( var i =0; i < arr.length; i++)
{
if(arr[i].length > maxLength)
{
maxLength= arr[i].length
}
}
return maxLength
}
// #108
/*
Write a function called "getSmallestElementAtProperty".
Given an object and a key, "getSmallestElementAtProperty" returns the smallest element
in the array located at the given key.
Notes:
* If the array is empty, it should return undefined.
* If the property at the given key is not an array, it should return undefined.
* If there is no property at the key, it should return undefined.
var obj = {
key: [2, 1, 5]
};
var output = getSmallestElementAtProperty(obj, 'key');
console.log(output); // --> 1
*/
function getSmallestElementAtProperty(obj, key) {
if ((typeof obj[key] != "undefined") && Array.isArray(obj[key]) && obj[key].length > 0) {
var smallest = obj[key][0]
for (var elem in obj[key]){
if (obj[key][elem] < smallest)
{
smallest = obj[key][elem]
}
}
return smallest
}
else
{
return undefined
}
}
// #109
/*
Write a function called "getLargestElementAtProperty".
Given an object and a key, "getLargestElementAtProperty" returns the largest
element in the array located at the given key.
Notes:
* If the array is empty, it should return undefined.
* If the property at the given key is not an array, it should return undefined.
* If there is no property at the key, it should return undefined.
var obj = {
key: [1, 2, 4]
};
var output = getLargestElementAtProperty(obj, 'key');
console.log(output); // --> 4
*/
function getLargestElementAtProperty(obj, key) {
if ((typeof obj[key] != "undefined") && (Array.isArray(obj[key]) && obj[key].length >0))
{
var ans = obj[key][0]
for (var elem in obj[key])
{
if( obj[key][elem] > ans)
ans = obj[key][elem]
}
return ans
}
else {return undefined}
}
// #110
/*
Write a function called "getAllButLastElementOfProperty".
Given an object and a key, "getAllButLastElementOfProperty" returns an array containing all
but the last element of the array located at the given key.
Notes:
* If the array is empty, it should return an empty array.
* If the property at the given key is not an array, it return an empty array.
* If there is no property at the key, it should return an empty array.
var obj = {
key: [1, 2, 3]
};
var output = getAllButLastElementOfProperty(obj, 'key');
console.log(output); // --> [1,2]
*/
function getAllButLastElementOfProperty(obj, key) {
if ((typeof obj[key] != "undefined") && (Array.isArray(obj[key]) && obj[key].length >0))
{
arr = obj[key]
return arr.slice(0, arr.length-1)
}
else return []
}
// #111
/*
Write a function called "getElementOfArrayProperty".
Given an object, a key, and a numerical index, "getElementOfArrayProperty" returns the value of the element
at the given index of the array located within the given object at the given key.
Notes:
* If the array is empty, it should return undefined.
* If the given index is out of range of the array located at the given key, it should return undefined.
* If the property at the given key is not an array, it should return undefined.
* If there is no property at the key, it should return undefined.
var obj = {
key: ['Jamil', 'Albrey']
};
var output = getElementOfArrayProperty(obj, 'key', 0);
console.log(output); // --> 'Jamil'
*/
function getElementOfArrayProperty(obj, key, index) {
if ((typeof obj[key] != "undefined") && (Array.isArray(obj[key]) && obj[key].length))
{
return obj[key][index]
}
else return undefined
}
// #112
/*
Write a function called "squareElements".
Given a array of numbers, "squareElements" should return a new array where each element
is the square of the element of the given array.
var output = squareElements([1, 2, 3]);
console.log(output); // --> [1, 4, 9]
*/
function squareElements(arr) {
var ans =[]
for ( var i=0; i< arr.length; i++)
ans.push(Math.pow(arr[i], 2))
return ans
}
// #113
/*
Write a function called "filterOddElements".
Given an array of numbers, "filterOddElements" returns an array containing only the odd numbers of the given array.
var output = filterOddElements([1, 2, 3, 4, 5]);
console.log(output); // --> [1, 3, 5]
*/
function filterOddElements(arr) {
var odds =[]
for (var i =0; i<arr.length; i++)
{
if(arr[i] %2 !=0) odds.push(arr[i])
}
return odds
}
// alternative solution to #113
// #114
/*
Write a function called "computeProductOfAllElements".
Given an array of numbers, "computeProductOfAllElements" returns the products of all the elements in the given array.
Notes:
* If given array is empty, it should return 0.
var output = computeProductOfAllElements([2, 5, 6]);
console.log(output); // --> 60
*/
function computeProductOfAllElements(arr) {
if (arr.length >0){
var product =1
for (var i =0; i<arr.length; i++)
{
product *= arr[i]
}
return product
}
else return 0
}
// # 115
/*
Write a function called "filterEvenElements".
Given an array of numbers, "filterEvenElements" returns an array containing only the even numbers of the given array.
var output = filterEvenElements([2, 3, 4, 5, 6]);
console.log(output); // --> [2, 4, 6]
*/
function filterEvenElements(arr) {
var result = [];
arr.filter(function (num){
if (num % 2 === 0){
result.push(num);
}
});
return result;
}
# 116
/*
Write a function called "getLengthOfShortestElement".
Given an array, "getLengthOfShortestElement" returns the length of the shortest string in the given array.
Notes:
* It should return 0 if the array is empty.
var output = getLengthOfShortestElement(['one', 'two', 'three']);
console.log(output); // --> 3
*/
function getLengthOfShortestElement(arr) {
if(arr.length ===0) return 0
var shortest = arr[0].length
for (var i =0; i<arr.length; i++)
{
if(arr[i].length < shortest)
{
shortest=arr[i].length
}
}
return shortest
}
// #117
/*
Write a function called "getLongestElement".
Given an array, "getLongestElement" returns the longest string in the given array.
Notes:
* If there are ties, it returns the first element to appear.
* If the array is empty, tt should return an empty string.
var output = getLongestElement(['one', 'two', 'three']);
console.log(output); // --> 'three'
*/
function getLongestElement(arr) {
var ansArr =[]
var longest = arr[0].length
for ( var i =0; i<arr.length; i++)
{
if(arr[i].length > longest)
{
longest = arr[i].length
ansArr=[]
ansArr.push(arr[i])
}
else if ( arr[i].length === longest)
{
ansArr.push(arr[i])
}
}
return ansArr[0]
}
// #118
/*
Write a function called "findSmallestElement".
Given an array of numbers, "findSmallestElement" returns the smallest number within the given array.
Notes:
* If the given array is empty, it should return 0.
var output = findSmallestElement([4, 1, 9, 10]);
console.log(output); // --> 1
*/
function findSmallestElement(arr) {
if(arr.length ===0) return 0
var smallest=arr[0]
for (var i =0; i<arr.length; i++)
{
if (arr[i] <smallest)
{
smallest=arr[i]
}
}
return smallest
}
// #119
/*
Write a function called "findShortestElement".
Given an array, "findShortestElement" returns the shortest string within the given array.
Notes:
* If there are ties, it should return the first element to appear.
* If the given array is empty, it should return an empty string.
var output = findShortestElement(['a', 'two', 'three']);
console.log(output); // --> 'a'
*/
function findShortestElement(arr) {
var ansArr =[]
var shortest= arr[0].length
for (var i =0; i<arr.length; i++)
{
if(arr[i].length < shortest)
{
shortest=arr[i].length
ansArr=[]
ansArr.push(arr[i])
}
else if (arr[i].length === shortest)
{
ansArr.push(arr[i])
}
}
return ansArr[0]
}
// #120
/*
Write a function called "getLargestElement".
Given an array, "getLargestElement" returns the largest number in the given array.
Notes:
* It should return 0 if the array is empty.
var output = getLargestElement([5, 2, 8, 3]);
console.log(output); // --> 8;
*/
function getLargestElement(arr) {
if(arr.length ===0) return 0
var largest=arr[0]
for (var i=0; i <arr.length; i++)
{
if (arr[i]> largest) largest= arr[i]
}
return largest
}
// #121
/*
Write a function called "computeSumOfAllElements".
Given an array of numbers, "computeSumOfAllElements" returns the sum of all the elements in the given array.
var output = computeSumOfAllElements([1, 2, 3])
console.log(output); // --> 6
*/
function computeSumOfAllElements(arr) {
var sum =0
for (var i =0; i<arr.length; i++)
{
sum += arr[i]
}
return sum
}
// # 122
/*
Write a function called "calculateBillTotal".
Given the pre tax and pre tip amount of a meal, "calculateBillTotal" returns the total amount due after tax and tip.
Notes:
* Assume that sales tax is 9.5% and tip is 15%.
* Do NOT tip on the sales tax, only on the pre tip amount.
var output = calculateBillTotal(20);
console.log(output); // --> 24.9
*/
function calculateBillTotal(preTaxAndTipAmount) {
var billTotal = preTaxAndTipAmount *0.15 + preTaxAndTipAmount*0.095 +preTaxAndTipAmount
return billTotal
}
// #123
function getStringLength(string) {
var arr = string.split("");
var count = 0;
for(var i in arr){
count++;
}
return count;
}
function getStringLength(string) {
var i = 0;
while(string[i]){
i++;
}
return i;
}
// #124
/*
Write a function called "joinArrayOfArrays".
Given an array of arrays, "joinArrayOfArrays" returns a single array containing the elements of the nested arrays.
var output = joinArrayOfArrays([[1, 4], [true, false], ['x', 'y']]);
console.log(output); // --> [1, 4, true, false, 'x', 'y']
You should be familiar with the "concat" method for this problem.
*/
function joinArrayOfArrays(arr) {
var result = [].concat.apply([], arr);
return result;
}
// #125
/*
Write a function called "getProductOfAllElementsAtProperty".
Given an object and a key, "getProductOfAllElementsAtProperty" returns the
product of all the elements in the array located at the given key.
Notes:
* If the array is empty, it should return 0.
* If the property at the given key is not an array, it should return 0.
* If there is no property at the given key, it should return 0.
var obj = {
key: [1, 2, 3, 4]
};
var output = getProductOfAllElementsAtProperty(obj, 'key');
console.log(output); // --> 24
*/
function getProductOfAllElementsAtProperty(obj, key) {
if ((typeof obj[key] != "undefined") && (Array.isArray(obj[key]) && obj[key].length>0))
{
var prod =1
for (var elem in obj[key])
{
prod *= obj[key][elem]
}
return prod
}
else return 0
}
// #126
/*
Write a function called "sumDigits".
Given a number, "sumDigits" returns the sum of all its digits.
var output = sumDigits(1148);
console.log(output); // --> 14
If the number is negative, the first digit should count as negative.
var output = sumDigits(-316);
console.log(output); // --> 4
Notes:
* In order to use some of the methods that will be most helpful to you,
you will most likely want to do some string to number conversion and vice versa.
* Be sure to familiarize yourself with the "toString" method, as well as the "Number" function.
*/
function sumDigits(num) {
num = num.toString()
var sum =0
if (num[0] ==='-'){
for (var i =2; i < num.length; i++){
sum += Number(num[i])
}
sum += -Number(num[1])
return sum
}
else{
for (var i =0; i < num.length; i++){
sum += Number(num[i])
}
return sum
}
}
// #127
/*
Write a function called "getSumOfAllElementsAtProperty".
Given an object and a key, "getSumOfAllElementsAtProperty" returns the sum of
all the elements in the array located at the given key.
Notes:
* If the array is empty, it should return 0.
* If the property at the given key is not an array, it should return 0.
* If there is no property at the key, it should return 0.
var obj = {
key: [4, 1, 8]
};
var output = getSumOfAllElementsAtProperty(obj, 'key');
console.log(output); // --> 13
*/
function getSumOfAllElementsAtProperty(obj, key) {
if((typeof obj[key] != "undefined")&& (Array.isArray(obj[key]) && obj[key].length >0))
{
var sum =0
for (var elem in obj[key])
{
sum += obj[key][elem]
}
return sum
}
else return 0
}
// #128
/*
Write a function called "findShortestWordAmongMixedElements".
Given an array, "findShortestWordAmongMixedElements" returns the shortest string within the given array.
Notes:
* If there are ties, it should return the first element to appear in the given array.
* Expect the given array to have values other than strings.
* If the given array is empty, it should return an empty string.
* If the given array contains no strings, it should return an empty string.
var output = findShortestWordAmongMixedElements([4, 'two', 2, 'three']);
console.log(output); // --> 'two'
*/
function findShortestWordAmongMixedElements(arr) {
var result =""
var short = 1000
for (var i =0; i<arr.length; i++)
{
if (typeof arr[i] === "string")
{
if(arr[i].length <short)
{
short = arr[i].length
result = arr[i]
}
}
}
return result
}
// #129
/*
Write a function called "findSmallestNumberAmongMixedElements".
Given an array of mixed elements, "findSmallestNumberAmongMixedElements" returns
the smallest number within the given array.
Notes:
* If the given array is empty, it should return 0.
* If the array contains no numbers, it should return 0.
var output = findSmallestNumberAmongMixedElements([4, 'lincoln', 9, 'octopus']);
console.log(output); // --> 4
*/
function findSmallestNumberAmongMixedElements(arr) {
var result = 0;
var count = 100;
var num;
for (var i = 0; i < arr.length; i++){
if (typeof (arr[i]) === "number"){
num = arr[i];
if (num < count){
count = num;
result = num;
}
}
}
return result;
}
// #130
/*
Write a function called "getLongestWordOfMixedElements".
Given an array of mixed types, "getLongestWordOfMixedElements" returns the longest string in the given array.
Notes:
* If the array is empty, it should return an empty string ("").
* If the array contains no strings; it should return an empty string.
var output = getLongestWordOfMixedElements([3, 'word', 5, 'up', 3, 1]);
console.log(output); // --> 'word'
*/
function getLongestWordOfMixedElements(arr) {
var ans =""
var longest =0
for ( var i =0; i<arr.length; i++)
{
if (typeof arr[i] === "string")
{
if (arr[i].length > longest)
{
ans = arr[i]
longest = arr[i].length
}
}
}
return ans
}
// #131
/*
Write a function called "getLargestNumberAmongMixedElements".
Given any array, "getLargestNumberAmongMixedElements" returns the largest number in the given array.
Notes:
* The array might contain values of a type other than numbers.
* If the array is empty, it should return 0.
* If the array contains no numbers, it should return 0.
var output = getLargestNumberAmongMixedElements([3, 'word', 5, 'up', 3, 1]);
console.log(output); // --> 5
*/
function getLargestNumberAmongMixedElements(arr) {
var largest = -100;
var result = 0;
for (var i = 0; i < arr.length; i++){
if(typeof arr[i] === "number"){
if (arr[i] > largest){
largest = arr[i];
result = arr[i];
}
}
}
return result;
}
// #132
/*
Write a function called "computeSummationToN".
Given a number, "computeSummationToN" returns the sum of sequential numbers leading up to the given number, beginning at 0.
Notes:
* If n = 4, it should calculate the sum of 1 + 2 + 3 + 4, and return 10.
var output = computeSummationToN(6);
console.log(output); // --> 21
*/
function computeSummationToN(n) {
var sum =0
for (var i =1; i <=n; i++)
{
sum += i
}
return sum
}
// #138
/*
Write a function called "computeCompoundInterest".
Given a principal, an interest rate, a compounding frequency, and a time (in years),
"computeCompoundInterest" returns the amount of compound interest generated.
var output = computeCompoundInterest(1500, .043, 4, 6);
console.log(output); // --> 438.8368221341061
Reference:
https://en.wikipedia.org/wiki/Compound_interest#Calculation_of_compound_interest
This shows the formula used to calculate the total compound interest generated.
*/
// #139
function computeCompoundInterest(principal, interestRate, compoundingFrequency, timeInYears) {
var result =(1 + (interestRate/compoundingFrequency));
var totalResult = principal * Math.pow(result, (timeInYears * compoundingFrequency));
return totalResult - principal;
}
// #140
function modulo(num1, num2) {
if(isNaN(num1) || isNaN(num2) || num2 === 0) {
return NaN;
}
if (num1 === -1) {
return -1;
}
if (num1 < 0) {
num1 = Math.abs(num1);
num2 = Math.abs(num2);
return -modulo(num1 - num2, num2);
}
num1 = Math.abs(num1);
num2 = Math.abs(num2);
if (num1 === 0) {
return 0;
} else if (num2 > num1) {
return num1;
} else {
return modulo(num1 - num2, num2);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment