- Notifications
You must be signed in to change notification settings - Fork47
Hello JavaScript code newbie! In this repository I'm proposing you a series of coding challenges that will help you practice the basic language constructs and algorithms.
NotificationsYou must be signed in to change notification settings
jahidulislamzim/JavaScriptCodingChallenges
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
functionaddition(a,b){//Write Your solution Here};console.log(addition(10,20));// 30console.log(addition(30,20));// 50console.log(addition(10,90));// 100
Solution
functionaddition(a,b){letadd=a+b;return(add)};
functionhowManySeconds(hours){//Write Your solution Here};console.log(howManySeconds(12));// 43200console.log(howManySeconds(8));// 28800console.log(howManySeconds(3));// 10800
Solution
functionhowManySeconds(hours){lethoursToSeconds=(hours*3600);return(hoursToSeconds)};
functionconvert(minutes){//Write Your solution Here};console.log(convert(30));// 1800console.log(convert(10));// 600console.log(convert(20));// 1200
Solution
functionconvert(minutes){letseconds=minutes*60;return(seconds)};
functionfootballPoints(wins,draws,losses){//Write Your solution Here};console.log(footballPoints(4,3,1));// 15console.log(footballPoints(10,5,0));// 35console.log(footballPoints(11,0,9));// 33
Solution
functionfootballPoints(wins,draws,losses){letpoints=(wins*3)+(draws*1)+(losses*0)return(points)};
functionbitwiseAND(n1,n2){//Write Your solution Here};functionbitwiseOR(n1,n2){//Write Your solution Here};functionbitwiseXOR(n1,n2){//Write Your solution Here};console.log(bitwiseAND(10,20));// 0console.log(bitwiseOR(10,20));// 30console.log(bitwiseXOR(10,20));// 30
Solution
functionbitwiseAND(n1,n2){letanswer=n1&n2;return(answer);};functionbitwiseOR(n1,n2){letanswer=n1|n2;return(answer);};functionbitwiseXOR(n1,n2){letanswer=n1^n2;return(answer);};
functiongetFirstValue(arr){//Write Your solution Here};console.log(getFirstValue(["Saab","Volvo","BMW"]));// Saabconsole.log(getFirstValue([3,5,1]));// 3console.log(getFirstValue(['hello','world','welcome']));// hello
Solution
functiongetFirstValue(arr){returnarr[0];};
07. Create a function that takes a number as an argument, increments the number by +1 and returns the result.
functionaddition(num){//Write Your solution Here};console.log(addition(5));// 6console.log(addition(100));// 101console.log(addition(99));// 100
Solution
functionaddition(num){letnumPlusOne=num+1;return(numPlusOne)};
08. Given two numbers, return true if the sum of both numbers is less than 100. Otherwise return false.
functionlessThan100(a,b){//Write Your solution Here};console.log(lessThan100(10,20));// trueconsole.log(lessThan100(50,60));// falseconsole.log(lessThan100(20,50));// true
Solution
functionlessThan100(a,b){if(a+b<100){returntrue;}else{returnfalse;}};
functionisSameNum(num1,num2){//Write Your solution Here};console.log(isSameNum(30,30));// trueconsole.log(isSameNum(20,40));// falseconsole.log(isSameNum(50,50));// true
Solution
functionisSameNum(num1,num2){if(num1===num2){returntrue;}else{returnfalse;}};
10. Create a function that takes a number (step) as an argument and returns the amount of matchsticks in that step.
functionmatchHouses(step){//Write Your solution Here};console.log(matchHouses(5));// 26console.log(matchHouses(0));// 0console.log(matchHouses(10));// 51
Solution
functionmatchHouses(step){if(step>0){letmatchSticks=((step*6)-(step-1));return(matchSticks)}else{letmatchSticks=0;return(matchSticks)}};
functionsquared(a){//Write Your solution Here};console.log(squared(6));// 36console.log(squared(9));// 81console.log(squared(4));// 16
Solution
functionsquared(a){return(a*a);};
functionfindPerimeter(height,width){//Write Your solution Here};console.log(findPerimeter(20,50));// 140console.log(findPerimeter(80,30));// 220console.log(findPerimeter(10,40));// 100
Solution
functionfindPerimeter(height,width){letperimeter=2*(height+width);return(perimeter)};
functionaddUp(num){//Write Your solution Here};console.log(addUp(10));// 55console.log(addUp(40));// 820console.log(addUp(15));// 120
Solution
functionaddUp(num){letsum=0;for(i=0;i<=num;i++){sum+=i;}return(sum)};
14. Create a function that takes in three arguments (prob, prize, pay) and returns true if prob * prize > pay; otherwise return false.
functionprofitableGamble(prob,prize,pay){//Write Your solution Here};console.log(profitableGamble(2,10,20));// falseconsole.log(profitableGamble(5,10,40));// trueconsole.log(profitableGamble(6,3,30));// false
Solution
functionprofitableGamble(prob,prize,pay){if(prob*prize>pay){return(true)}else{return(false)}};
functionminMax(arr){//Write Your solution Here};console.log(minMax([2,-1,5]));// [ -1, 5 ]console.log(minMax([0,5,2]));// [ 0, 5 ]console.log(minMax([2,-5,-1]));// [ -5, 2 ]
Solution
functionminMax(arr){arr.sort(function(a,b){return(a-b)})return[arr[0],arr[arr.length-1]]};
functioncanNest(arr1,arr2){//Write Your solution Here};console.log(canNest([3,1],[4,0]));// trueconsole.log(canNest([9,9,8],[8,9]));// falseconsole.log(canNest([1,2,3,4],[0,6]));// true
Solution
functioncanNest(arr1,arr2){arr1.sort(function(a,b){return(a-b)});arr2.sort(function(a,b){return(a-b)});letarr1MinMax=[arr1[0],arr1[arr1.length-1]];letarr2MinMax=[arr2[0],arr2[arr2.length-1]];if(arr1MinMax[0]>arr2MinMax[0]&&arr1MinMax[1]<arr2MinMax[1]){returntrue}else{returnfalse}};
functionnumberSquares(n){//Write Your solution Here};console.log(numberSquares(4));// 30console.log(numberSquares(5));// 55console.log(numberSquares(6));// 91
18. Your function will be passed two functions, f and g, that don't take any parameters. Your function has to call them, and return a string which indicates which function returned the larger number.
functionwhichIsLarger(f,g){//Write Your solution Here};console.log(whichIsLarger(()=>25,()=>15));// fconsole.log(whichIsLarger(()=>25,()=>25));// neitherconsole.log(whichIsLarger(()=>25,()=>50));// g
Solution
functionwhichIsLarger(f,g){if(f()>g()){return('f')}elseif(g()>f()){return('g')}elseif(f()===g()){return('neither')}};
19. Christmas Eve is almost upon us, so naturally we need to prepare some milk and cookies for Santa! Create a function that accepts a Date object and returns true if it's Christmas Eve (December 24th) and false otherwise. Keep in mind JavaScript's Date month is 0 based, meaning December is the 11th month while January is 0.
functiontimeForMilkAndCookies(date){//Write Your solution Here};console.log(timeForMilkAndCookies(newDate(3000,11,24)));//trueconsole.log(timeForMilkAndCookies(newDate(2013,0,23)));//falseconsole.log(timeForMilkAndCookies(newDate(3000,11,24)));//true
Solution
functiontimeForMilkAndCookies(date){returndate.getMonth()===11&&date.getDate()===24;};
20. function that takes a two-digit number and determines if it's the largest of two possible digit swaps.
functionlargestSwap(num){//Write Your solution Here};console.log(largestSwap(14));//falseconsole.log(largestSwap(53));//trueconsole.log(largestSwap(-27));//false
Solution
functionlargestSwap(num){letnum1=num+"";letnum2=num1.split("").reverse().join("");if(num1>=num2){returntrue;}if(num1<num2){returnfalse;}};functionlargestSwap(num){letc=num.toString();leta=[];letb=0;for(leti=0;i<c.length;i++){a.push(c[c.length-1-i]);b+=a[i];}letd=parseInt(b);if(d>num){returnfalse;}elsereturntrue;};
21. function that takes two strings as arguments and returns the number of times the first string (the single character) is found in the second string.
functioncharCount(myChar,str){//Write Your solution Here};console.log(charCount("a","largest"));//1console.log(charCount("c","Chamber of secrets"));// 2console.log(charCount("b","big fat bubble"));//4
Solution
functioncharCount(myChar,str){leta=0;for(leti=0;i<str.length;i++){if(myChar.toLowerCase()===str.toLowerCase()[i]){a+=1;}}returna};
functionrepetition(txt,n){//Write Your solution Here};console.log(repetition('zim',5));//zimzimzimzimzimconsole.log(repetition('zoy',2));//zoyzoyconsole.log(repetition('akib',7));//akibakibakibakibakibakibakib
Solution
functionrepetition(txt,n){letreptxt=""while(n>0){reptxt+=txtn--;}returnreptxt};
23. function that takes an array of non-negative integers and strings and return a new array without the strings.
functionfilterArray(arr){//Write Your solution Here};console.log(filterArray([1,'z',4,5,'i',9,'m']));//[ 1, 4, 5, 9 ]console.log(filterArray([8,'z',1,'8','i',9,'m']));//[ 8, 1, 9 ]console.log(filterArray([7,'1','z',0,'i',9,'m']));//[ 7, 0, 9 ]
Solution
functionfilterArray(arr){letfilteredArray=arr.filter(item=>typeofitem==="number");returnfilteredArray};functionfilterArray(arr){letfilteredArr=[];for(leti=0;i<arr.length;i++){if(typeofarr[i]!=="string"){filteredArr.push(arr[i])}}returnfilteredArr};
24. Write a function that take a string and write a regular expression inner function that returns the value that matches every red flag and blue flag in this string.
functionmatchFlag(str){//Write Your solution Here};console.log(matchFlag("yellow flag red flag blue flag green flag"));//[ 'red flag', 'blue flag' ]console.log(matchFlag("yellow flag green flag orange flag white flag"));//nullconsole.log(matchFlag("yellow flag blue flag green flag"));//[ 'blue flag' ]
Solution
functionmatchFlag(str){letREGEXP=/redflag|blueflag/g;returnstr.match(REGEXP);};
25. Write a function that take a string and write a RegExp to find ellipsis: 3 (or more?) dots in a row in this string.
functionmatchEllipsis(str){//Write Your solution Here};console.log(matchEllipsis("Hello!... How goes?....."));//[ '...', '.....' ]console.log(matchEllipsis("good morning!..... How goes?."));// [ '.....' ]console.log(matchEllipsis("good night!.......... How goes?..."));// [ '..........', '...' ]
Solution
functionmatchEllipsis(str){letREGEXP=/\.{3,}/g;returnstr.match(REGEXP);};
26. Write a function that returns 0 if the input is 1, and returns 1 if the input is 0. Try completing this challenge without using any:
functionflip(y){//Write Your solution Here};console.log(flip(1));// 0console.log(flip(0));// 1
Solution
functionflip(y){letx=y-1;return(Math.abs(x))};
27. Create a function that takes a string and returns a string in which each character is repeated once.
functiondoubleChar(str){//Write Your solution Here};console.log(doubleChar('jahidul'));//jjaahhiidduullconsole.log(doubleChar('islam'));//iissllaammconsole.log(doubleChar('zim'));//zziimm
Solution
functiondoubleChar(str){letdoubleString='';for(leti=0;i<str.length;i++){doubleString+=str[i]+str[i]}returndoubleString};functiondoubleChar(str){letarray=str.split("");letarray2=array.map(x=>x.repeat(2));letdoubleString=array2.join("");returndoubleString};
functionfactorial(num){//Write Your solution Here};console.log(factorial(5));//120console.log(factorial(10));//3628800console.log(factorial(8));//40320
Solution
functionfactorial(num){letfact=1;for(leti=0;i<num;i++){fact*=(num-i);}returnfact};functionfactorial(num){if(num<0)return-1;elseif(num==0)return1;else{return(num*factorial(num-1));}};functionfactorial(num){letresult=num;if(num===0||num===1)return1;while(num>1){num--;result*=num;}returnresult;};functionfactorial(num){letfact=num;if(num===0||num===1)return1;for(leti=num-1;i>=1;i--){fact*=i;}returnfact;};
29. Take an array of integers (positive or negative or both) and return the sum of the absolute value of each element.
functiongetAbsSum(arr){//Write Your solution Here};console.log(getAbsSum([1,-4,3,8,0]));// 16console.log(getAbsSum([1,3,0,-8,0]));// 12console.log(getAbsSum([1,-4,-3,8,0]));//16
Solution
functiongetAbsSum(arr){letabsSum=0;for(vari=0;i<arr.length;i++){absSum+=Math.abs(arr[i]);}returnabsSum;};
30. Write a function that take a string and write a REGEXP that matches any characters except letters, digits and spaces.
functionmatchAny(str){//Write Your solution Here};console.log(matchAny('Csxdzontains_underscore '));//[ '_' ]console.log(matchAny('Csxdzontains_underscore $ * P'));//[ '_', '$', '*' ]
Solution
functionmatchAny(str){constREGEXP=/[^a-z0-9]/gi;returnstr.match(REGEXP)};
31. Create a function that takes a string and returns the number (count) of vowels contained within it.
functioncountVowels(str){//Write Your solution Here};console.log(countVowels('Jahidul Islam zim'));// 6console.log(countVowels('returns the number of vowels'));// 8console.log(countVowels('JavaScript Coding Challenges'));// 8
Solution
functioncountVowels(str){letcount=0;letvowlStr=str.toLowerCase().match(/(a|e|i|o|u)/g);for(leti=0;i<vowlStr.length;i++){count+=1;}returncount;};
32. Create a function that takes two vectors as arrays and checks if the two vectors are orthogonal or not. The return value is boolean. Two vectors a and b are orthogonal if their dot product is equal to zero.
functionisOrthogonal(arr1,arr2){//Write Your solution Here};console.log(isOrthogonal([1,-2,4],[2,5,2]));//trueconsole.log(isOrthogonal([1,-2,5],[2,5,2]));//falseconsole.log(isOrthogonal([1,2,4],[-2,5,-2]));//true
Solution
functionisOrthogonal(arr1,arr2){letortho=0;for(i=0;i<arr1.length;i++){ortho+=arr1[i]*arr2[i]}if(ortho===0){returntrue}returnfalse};
33. Given an object of how many more pages each ink color can print, output the maximum number of pages the printer can print before any of the colors run out.
functioninkLevels(inks){//Write Your solution Here};console.log(inkLevels({cyan:50,magenta:12,yellow:60}));// 12console.log(inkLevels({cyan:50,magenta:120,yellow:60}));// 50console.log(inkLevels({cyan:50,magenta:12,yellow:8}));// 8
Solution
functioninkLevels(inks){returnMath.min(...Object.values(inks));};
functionremoveVowels(str){//Write Your solution Here};console.log(removeVowels('Jahidul Islam Zim'));//Jhdl slm Zmconsole.log(removeVowels('a new string with all vowels'));// nw strng wth ll vwlsconsole.log(removeVowels('Create a function'));//Crt fnctn
Solution
functionremoveVowels(str){letnewArr=str.match(/[^aeiouAEIOU]/g);letnewString=newArr.join('');returnnewString};
35. Create a function that takes an array of arrays with numbers. Return a new (single) array with the largest numbers of each.
functionfindLargestNums(arr){//Write Your solution Here};console.log(findLargestNums([[3,6],[10,20],[-1,7]]));//[ 6, 20, 7 ]console.log(findLargestNums([[8,6],[1,0],[10,-7]]));//[ 8, 1, 10 ]console.log(findLargestNums([[3,34],[10,22],[-1,-7]]));//[ 34, 22, -1 ]
Solution
functionfindLargestNums(arr){letnewArr=[]for(leti=0;i<arr.length;i++){newArr.push(Math.max(...arr[i]));}returnnewArr};
36. Given an array of scrabble tiles, create a function that outputs the maximum possible score a player can achieve by summing up the total number of points for all the tiles in their hand. Each hand contains 7 scrabble tiles.
functionmaximumScore(tileHand){//Write Your solution Here};console.log(maximumScore([{tile:"N",score:1},{tile:"K",score:5},{tile:"Z",score:10},]));//16console.log(maximumScore([{tile:"N",score:9},{tile:"K",score:5},{tile:"Z",score:40},]));//54console.log(maximumScore([{tile:"N",score:1},{tile:"K",score:65},{tile:"Z",score:10},]));//76
Solution
functionmaximumScore(tileHand){letscore=0;for(leti=0;i<tileHand.length;i++){score+=tileHand[i].score;}returnscore;};
37. Assume a program only reads .js or .jsx files. Write a function that accepts a file path and returns true if it can read the file and false if it can't.
functionisJS(path){//Write Your solution Here};console.log(isJS('file.jsx'));//trueconsole.log(isJS('file.jsg'));//falseconsole.log(isJS('file.js'));//true
Solution
functionisJS(path){letextension=path.match(/[^.]+$/g)[0]if(extension==='js'||extension==='jsx'){returntrue;}returnfalse;};
38. A farmer is asking you to tell him how many legs can be counted among all his animals. The farmer breeds three species:
The farmer has counted his animals and he gives you a subtotal for each species. You have to implement a function that returns the total number of legs of all the animals.
functionanimals(chickens,cows,goats){//Write Your solution Here};console.log(animals(2,3,5))// 36console.log(animals(1,2,3))// 22console.log(animals(5,2,8))// 50
Solution
functionanimals(chickens,cows,goats){returnchickens*2+cows*4+goats*4;};
39.Create a function that returns the number of frames shown in a given number of minutes for a certain FPS.
functionframes(minutes,fps){//Write Your solution Here};console.log(frames(1,1));//60console.log(frames(10,1));//600console.log(frames(10,25));//15000
Solution
functionframes(minutes,fps){returnminutes*60*fps;};
40.Create a function that takes two arguments. Both arguments are integers, a and b. Return true if one of them is 10 or if their sum is 10.
functionmakesTen(a,b){//Write Your solution Here};console.log(makesTen(1,1));//60console.log(makesTen(10,1));//600console.log(makesTen(10,25));//15000
Solution
functionmakesTen(a,b){if(a==10||b==10){returntrue;}elseif(a+b==10){returntrue;}else{returnfalse;};};
41.Create a function that takes two strings as arguments and return either true or false depending on whether the total number of characters in the first string is equal to the total number of characters in the second string.
functioncomp(str1,str2){//Write Your solution Here};console.log(comp("AB","CD"));//trueconsole.log(comp("ABC","DE"));//falseconsole.log(comp("WE","RT"));// true
Solution
functioncomp(str1,str2){if(str1.length===str2.length){returntrue;}returnfalse;};
42.A vehicle needs 10 times the amount of fuel than the distance it travels. However, it must always carry a minimum of 100 fuel before setting off. Create a function which calculates the amount of fuel it needs, given the distance.
functioncalculateFuel(n){//Write Your solution Here};console.log(calculateFuel(15));//150console.log(calculateFuel(23.5));//235console.log(calculateFuel(3));//100
Solution
functioncalculateFuel(n){letfuel=n*10;if(fuel>=100){returnfuel;};return100;};
43.Given an n-sided regular polygon n, return the total sum of internal angles (in degrees). n will always be greater than 2.
functionsumPolygon(n){//Write Your solution Here};console.log(sumPolygon(3));//180console.log(sumPolygon(4));//360console.log(sumPolygon(6));// 720
Solution
functionsumPolygon(n){return(n-2)*180;};
functiondivisibleByFive(n){//Write Your solution Here};console.log(divisibleByFive(5));//trueconsole.log(divisibleByFive(-55));//falseconsole.log(divisibleByFive(37));//true
Solution
functiondivisibleByFive(n){if(n%5===0){returntrue;};returnfalse;};
functionsumOfCubes(nums){//Write Your solution Here};console.log(sumOfCubes([1,2,3,4,5]));//255console.log(sumOfCubes([5,2,7,4,0]));//540console.log(sumOfCubes([1,6,3,9,5]));//1098
Solution
functionsumOfCubes(nums){varcubeSum=0;for(iinnums){cubeSum+=nums[i]*nums[i]*nums[i];};returncubeSum;;};
46.A group of friends have decided to start a secret society. The name will be the first letter of each of their names, sorted in alphabetical order. Create a function that takes in an array of names and returns the name of the secret society.
functionsocietyName(friends){//Write Your solution Here};console.log(societyName(['zim','zoy','shithil','akib']));//zzsaconsole.log(societyName(['Rakib','Taskin','shomrat','Prionty']));//RTsPconsole.log(societyName(['Ratul','Rakib','Ritu','Taj']));//RRRT
Solution
functionsocietyName(friends){letnameArr=friends.map((x)=>x.split(""));letletterArr="";for(leti=0;i<nameArr.length;i++){letterArr+=nameArr[i][0];};returnletterArr;};
functionisPrefix(word,prefix){//Write Your solution Here};functionisSuffix(word,suffix){//Write Your solution Here};console.log(isPrefix("automation","auto-"));//trueconsole.log(isPrefix("retrospect","sub-"));//falseconsole.log(isSuffix("arachnophobia","-phobia"));//trueconsole.log(isSuffix("vocation","-logy"));//false
Solution
functionisPrefix(word,prefix){returnword.startsWith(prefix.slice(0,-1));}functionisSuffix(word,suffix){returnword.endsWith(suffix.slice(1));}functionisPrefix(word,prefix){letprefixWord=prefix.slice(0,-1);letmainWord='';for(leti=0;i<prefixWord.length;i++){mainWord+=word[i];}if(prefixWord===mainWord){returntrue;}returnfalse;}functionisSuffix(word,suffix){letsuffixWord=suffix.slice(1);letmainWord='';letnewString='';for(leti=word.length-1;i>suffixWord.length;i--){mainWord+=word[i];}for(leti=mainWord.length-1;i>=0;i--){newString+=mainWord[i];}if(suffixWord===newString){returntrue;}returnfalse;}
functionhashPlusCount(str){//Write Your solution Here};console.log(hashPlusCount("###+"));//[ 3, 1 ]console.log(hashPlusCount("##+++#"));//[ 3, 3 ]console.log(hashPlusCount(""));//[ 0, 0 ]
Solution
functionhashPlusCount(str){lethash=(str.match(/#/g)||[]).length;letplus=(str.match(/\+/g)||[]).length;return[hash,plus];};
49. Create a function that takes an array of 10 numbers (between 0 and 9) and returns a string of those numbers formatted as a phone number (e.g. (555) 555-5555).
functionformatPhoneNumber(numbers){//Write Your solution Here};console.log(formatPhoneNumber([1,2,3,4,5,6,7,8,9,0]));//(123) 456-7890console.log(formatPhoneNumber([1,2,0,4,5,3,8,1,9,0]));//(120) 453-8190console.log(formatPhoneNumber([1,7,9,4,2,6,8,8,5,0]));//(179) 426-8850
Solution
functionformatPhoneNumber(numbers){numbers.splice(0,0,"(");numbers.splice(4,0,")");numbers.splice(5,0," ");numbers.splice(9,0,"-");letstr=numbers.join("");returnstr;};
50. Write a regular expression that matches only an even number. Numbers will be presented as strings.
functionmatchEven(str){//Write Your solution Here};console.log(matchEven("3458"));//8console.log(matchEven("3517"));//Undefinedconsole.log(matchEven("4902"));//2
Solution
functionmatchEven(num){letREGEXP=/[24680]$/;returnnum.match(REGEXP)?.[0];};
functionfirstVowel(str){//Write Your solution Here};console.log(firstVowel("zimislam"));//1console.log(firstVowel("akib"));//0console.log(firstVowel("shomrat"));//2
Solution
functionfirstVowel(str){letregex=/[aeiou]/gi;returnstr.search(regex);};
functionremovesDuplicateItems(arr){//Write Your solution Here};console.log(removesDuplicateItems(["A","B","A","C","D","C"]));//[ 'A', 'B', 'C', 'D' ]console.log(removesDuplicateItems([1,4,2,3,2,4,3,5]));//[ 1, 4, 2, 3, 5 ]console.log(removesDuplicateItems(["zim","zoy","zim","akib","shithil","akib"]));//[ 'zim', 'zoy', 'akib', 'shithil' ]
Solution
functionremovesDuplicateItems(arr){constsetArr=[...newSet(arr)];returnsetArr;};functionremovesDuplicateItems(arr){letunique=arr.filter((element,index)=>{returnarr.indexOf(element)===index;});returnunique;};functionremovesDuplicateItems(arr){letunique=[];arr.forEach((c)=>{if(!unique.includes(c)){unique.push(c);}});returnunique;};functionremovesDuplicateItems(arr){letoutputArray=[];letcount=0;letstart=false;for(j=0;j<arr.length;j++){for(k=0;k<outputArray.length;k++){if(arr[j]==outputArray[k]){start=true;}}count++;if(count==1&&start==false){outputArray.push(arr[j]);}start=false;count=0;}returnoutputArray;};functionremovesDuplicateItems(arr){for(leti=0;i<arr.length;i++){for(letj=i+1;j<arr.length;j++){if(arr[i]===arr[j]){for(letk=j;k<arr.length;k++){arr[k]=arr[k+1];}arr.length--;j--;}}}returnarr;};
53. Create a function that takes an array of numbers and returns a new array, sorted in ascending order (smallest to biggest).
functionsortNumsAscending(arr){//Write Your solution Here};console.log(sortNumsAscending([2,4,6,1,9,3,5,8,7,0]));//[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]console.log(sortNumsAscending([22,40,56,11,90]));//[ 11, 22, 40, 56, 90 ]console.log(sortNumsAscending([26,45,64,19,59,31]));//[ 19, 26, 31, 45, 59, 64 ]
Solution
functionsortNumsAscending(arr){if((arr===[])|(arr===null)){return[];}returnarr.sort(function(a,b){returna-b;});};functionsortNumsAscending(arr){for(leti=1;i<arr.length;i++)for(letj=0;j<i;j++)if(arr[i]<arr[j]){varx=arr[i];arr[i]=arr[j];arr[j]=x;}returnarr;}
54. Given a higher bound num, implement a function that returns an array with the sequence of numbers, after that every multiple of 4 has been amplified by 10.
functionamplify(num){//Write Your solution Here};console.log(amplify(12));//[1, 2, 3, 40, 5, 6, 7, 80, 9, 10, 11, 120]console.log(amplify(8));//[1, 2, 3, 40, 5, 6, 7, 80 ]console.log(amplify(15));//[1, 2, 3, 40, 5, 6, 7, 80, 9, 10, 11, 120,13, 14, 15]
Solution
functionamplify(num){letarr=[];for(leti=1;i<=num;i++){if(i%4===0){arr.push(i*10);}else{arr.push(i);}}returnarr;}
55. Given an array of 10 numbers, return the maximum possible total made by summing just 5 of the 10 numbers.
functionmaxTotal(nums){//Write Your solution Here};console.log(maxTotal([1,1,0,1,3,10,10,10,10,1]));//43console.log(maxTotal([0,0,0,0,10,0,3,0,100]));// 113console.log(maxTotal([1,2,3,2,5,6,9,8,9,10]));//42
Solution
functionmaxTotal(nums){letnums1=nums.sort(function(a,b){returna-b})letmax=0for(i=5;i<nums1.length;i++){max+=nums1[i];}returnmax;}
functionisValidZip(zip){//Write Your solution Here};console.log(isValidZip("393939"));//falseconsole.log(isValidZip("59001"));//trueconsole.log(isValidZip("853a7"));//false
Solution
functionisValidZip(zip){constREXEX=/^\d{5}$/;returnREXEX.test(zip);}
57. Create a function that takes a number as an argument and returns the highest digit in that number.
functionhighestDigit(number){//Write Your solution Here};console.log(highestDigit(3456));//6console.log(highestDigit(21098));//9console.log(highestDigit(56123));//6
Solution
consthighestDigit=(number)=>{letarr=(number.toString().split(''))returnMath.max(...arr)}
58. Create a function that takes a number as an argument and returns the highest digit in that number.
functionhighestDigit(number){//Write Your solution Here};console.log(highestDigit(3456));//6console.log(highestDigit(21098));//9console.log(highestDigit(56123));//6
Solution
consthighestDigit=(number)=>{letarr=(number.toString().split(''))returnMath.max(...arr)}
59. Given an array of scrabble tiles, create a function that outputs the maximum possible score a player can achieve by summing up the total number of points for all the tiles in their hand. Each hand contains 7 scrabble tiles.
functionmaximumScore(titleHand){//Write Your solution Here};console.log(maximumScore([{tile:"B",score:2},{tile:"V",score:4},{tile:"F",score:4},{tile:"U",score:1},{tile:"D",score:2},{tile:"O",score:1},{tile:"U",score:1}]));// 15console.log(maximumScore([{tile:"N",score:1},{tile:"K",score:5},{tile:"Z",score:10},{tile:"X",score:8},{tile:"D",score:2},{tile:"A",score:1},{tile:"E",score:1}]));// 28
Solution
constmaximumScore=(titleHand)=>{letmaxScore=0for(iintitleHand){maxScore+=titleHand[i].score;}returnmaxScore;}
60.Create a function that takes an array as an argument and returns true or false depending on whether the average of all elements in the array is a whole number or not.
constisAvgWhole=(arr)=>{//Write Your solution Here};console.log(isAvgWhole([1,3]));// trueconsole.log(isAvgWhole([1,2,3,4]));// falseconsole.log(isAvgWhole([1,5,6]));// trueconsole.log(isAvgWhole([1,1,1]));// trueconsole.log(isAvgWhole([9,2,2,5]));// false
Solution
constisAvgWhole=(arr)=>{letsum=0;for(iinarr){sum+=arr[i]}if(sum%(arr.length)===0){returntrue}returnfalse}
61.Create a function that takes an array of strings and return an array, sorted from shortest to longest.
constsortByLength=(arr)=>{//Write Your solution Here};console.log(sortByLength(["a","ccc","dddd","bb"]))//["a", "bb", "ccc", "dddd"]console.log(sortByLength(["apple","pie","shortcake"]))//["pie", "apple", "shortcake"]console.log(sortByLength(["may","april","september","august"]))//["may", "april", "august", "september"]
Solution
constsortByLength=(arr)=>{returnarr.sort(function(a,b){returna.length-b.length})}constsortByLength=(arr)=>{constn=arr.length;for(leti=0;i<n-1;i++){for(letj=0;j<n-i-1;j++){if(arr[j].length>arr[j+1].length){consttemp=arr[j];arr[j]=arr[j+1];arr[j+1]=temp;}}}returnarr;};
62. A value is omnipresent if it exists in every subarray inside the main array. Create a function that determines whether an input value is omnipresent for a given array.Create a function that takes an array of strings and return an array, sorted from shortest to longest.
constisOmnipresent=(arr,val)=>{//Write Your solution Here};console.log(isOmnipresent([[1,1],[1,3],[5,1],[6,1]],1));// trueconsole.log(isOmnipresent([[1,1],[1,3],[5,1],[6,1]],6));// falseconsole.log(isOmnipresent([[5],[5],[5],[6,5]],5));// trueconsole.log(isOmnipresent([[5],[5],[5],[6,5]],6));//false
Solution
constisOmnipresent=(arr,val)=>{for(iinarr){for(iinarr[i]){returnarr[i].includes(val)}}}
About
Hello JavaScript code newbie! In this repository I'm proposing you a series of coding challenges that will help you practice the basic language constructs and algorithms.
Topics
Resources
Uh oh!
There was an error while loading.Please reload this page.



