JavaScript | Coding Challenges Set #2 For Intermediate

Hello, again JavaScript code newbie! I am here with some new JavaScript Coding challenges for intermediate, Read and practice code by your own or just learn from solutions.

This set of JavaScript coding challenges set includes concepts like object oriented programming is used in solving this challenges.

You can also read our JavaScript | Intro To Job Titles

Coding Challenges Sets:

  1. For JavaScript coding challenges 1 to 26 JavaScript | Coding Challenge Set #1 For Beginners

Note: This blog is for Intermediate Level (object oriented programming)

Coding Challenge Set #2 For Intermediate

List of JavaScript coding challenge 27 to 53

27: Write a JavaScript function that will receive an array of numbers as argument and it should return a new array with distinct elements.

Click here for solution 1 View Code

Click here for solution 2 View Code

28: Write a JavaScript code to Calculate the sum of first 100 prime numbers.

Click here to View Code

29: Print the distance between the first 100 prime numbers in JavaScript.

Click here to View Code

30: Use JavaScript to create a function that will add two positive numbers of indefinite size. And the numbers are received as strings and the result should be also provided as string.

Click here for solution 1 View Code

Click here for solution 2 View Code

31: Create a function that will return the number of words in a text using JavaScript.

Click here to View Code

Click here to View Code

32: Make a function that will capitalize the first letter of each word in a text using JavaScript.

Click here to View Code

33: Calculate the sum of numbers received in a comma delimited string with JavaScript code.

Click here to View Code

34: Write a JavaScript code to create a function that will return an array with words inside a text.

Click here to View Code

35: Build a JavaScript function to convert a CSV text to a “bi-dimensional” array.

Click here to View Code

36: Create a function that converts a string to an array of characters with using JavaScript.

Click here to View Code

37: Use JavaScript code to create a function that will convert a string in an array containing the ASCII codes of each character.

Click here to View Code

38: Create a function that will convert an array containing ASCII codes in a string using JavaScript.

Click here to View Code

39: Use JavaScript code to implement the Caesar cypher.

Click here to View Code

40: Implement the bubble sort algorithm for an array of numbers using JavaScript.

Click here to View Code

41: Write JavaScript code to create a function to calculate the distance between two points defined by their x, y coordinates.

Click here to View Code

42: Write JavaScript code to Create a function that will return a Boolean value indicating if two circles defined by center coordinates and radius are intersecting.

Click here to View Code

43: Create a function that will receive a bi-dimensional array as argument and a number and will extract as a unidimensional array the column specified by the number using JavaScript.

Click here to View Code

44: Build a JavaScript function that will convert a string containing a binary number into a number.

Click here to View Code

45: Use JavaScript code to create a function to calculate the sum of all the numbers in a jagged array (array contains numbers or other arrays of numbers on an unlimited number of levels).

Click here to View Code

46: Find the maximum number in a jagged array of numbers or array of numbers using JavaScript.

Click here for solution 1 View Code

Click here for solution 2 View Code

47: Deep copy a jagged array with numbers or other arrays in a new array using JavaScript.

Click here to View Code

48: Build a JavaScript function to return the longest word(s) in a string.

Click here to View Code

49: Shuffle an array of strings using JavaScript.

Click here to View Code

50: Make a function that will receive n as argument and return an array of n unique random numbers from 1 to n using JavaScript.

Click here to View Code

51: Write JavaScript code to find the frequency of characters inside a string. Return the result as an array of objects. Each object has 2 fields: character and number of occurrences.

Click here to View Code

52: Use JavaScript code to calculate Fibonacci(500) with high precision (all decimals).

Click here to View Code

53: Calculate 70! with high precision (all digits) using JavaScript.

Click here to View Code

Thank you for reading and stay tune, stay connected and stay safe. Please support us by sharing the blog.

Useful blogs JavaScript | Intro To Job Titles

Read our other blogs on ITbulls.in

Previous Post

Leave a Reply

Your email address will not be published. Required fields are marked *

                    

var ar = getDistinctElements([1, 2, 3, 6, -1, 2, 9, 7, 10, -1, 100]);
console.log(ar);
function getDistinctElements(ar)
{
    var ar2 = [];   
    for(let i = 0; i < ar.length; i++)
    {
        if (!isInArray(ar[i], ar2))
        {
            ar2.push(ar[i]);
        }
    }
    return ar2;
}
function isInArray(n, ar)
{
    for(let i = 0; i < ar.length; i++)
    {
        if (ar[i] === n)
            return true;
    }
    return false;
}

                    

var ar = getDistinctElements([1, 2, 3, 6, -1, 2, 9, 7, 10, -1, 100]);
console.log(ar);
function getDistinctElements(ar)
{
    var ar2 = [];
    var lastIndex = ar.length - 1;
    for(let i = 0; i <= lastIndex; i++)
    {
        if (!isInArray(ar[i], ar, i + 1, lastIndex))
        {
            ar2.push(ar[i]);
        }
    }
    return ar2;
}
function isInArray(n, ar, fromIndex, toIndex)
{
    for(var i = fromIndex; i <= toIndex; i++)
    {
        if (ar[i] === n)
            return true;
    }
    return false;
}

                    

var n = 10;
console.log("Sum of first ", n, " primes is ", sumPrimes(10));
function sumPrimes(n)
{
    var foundPrimes = 0;
    var i = 2;
    var sum = 0;
    
    while(foundPrimes < n)
    {
        if (isPrime(i))
        {
            foundPrimes++;
            sum += i;
        }
        i++;
    }
    return sum;
}
// Returns true if number n is prime
function isPrime(n)
{
    if (n < 2)
        return false;
    if (n == 2)
        return true;
    var maxDiv = Math.sqrt(n);
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i === 0)
        {
            return false;
        }
    }
    return true;
}

                    

printDistances(100);
// Print distances between the first n prime numbers
function printDistances(n)
{
    var lastPrime = 2;
    var i = lastPrime + 1;
    var foundPrimes = 1;
    while(foundPrimes < n)
    {
        if (isPrime(i))
        {
            console.log(i - lastPrime, "\t", i, " - ", lastPrime);
            foundPrimes++;
            lastPrime = i;
        }
        i++;
    }
}
// Returns true if number n is prime
function isPrime(n)
{
    if (n < 2)
        return false;
    if (n == 2)
        return true;
    var maxDiv = Math.sqrt(n);
    for(var i = 2; i <= maxDiv; i++)
    {
        if (n % i === 0)
        {
            return false;
        }
    }
    return true;
}

                    

var n1 = "2909034221912398942349";
var n2 = "1290923909029309499";
var sum = add(n1, n2);
console.log(n1, "\n", n2, "\n", sum);
function add(sNumber1, sNumber2)
{
    var s = "";
    var carry = 0;
    var maxSize = Math.max(sNumber1.length, sNumber2.length);
    for(var i = 0; i < maxSize; i++)
    {
        var digit1 = digitFromRight(sNumber1, i);
        var digit2 = digitFromRight(sNumber2, i);
        var sum = digit1 + digit2 + carry;
        var digitSum = sum % 10;
        carry = sum >= 10 ? 1 : 0;
        s = digitSum.toString() + s;
    }
    if (carry > 0)
        s = carry + s;
    return s;
}
function digitFromRight(s, digitNo)
{
    if (digitNo >= s.length)
        return 0;       
    var char = s[ s.length - 1 - digitNo ];
    return parseInt(char);
}

                    

var n1 = "2909034221912398942349";
var n2 = "1290923909029309499";
var sum = add(n1, n2);
console.log(n1);
console.log(n2);
console.log(sum);
function add(sNumber1, sNumber2)
{
    var maxSize = Math.max(sNumber1.length, sNumber2.length);
    var s1 = sNumber1.padStart(maxSize, "0");
    var s2 = sNumber2.padStart(maxSize, "0");
    var s = "";
    var carry = 0;
    for(var i = maxSize - 1; i >= 0; i--)
    {
        var digit1 = parseInt(s1[i]);
        var digit2 = parseInt(s2[i]);
        var sum = digit1 + digit2 + carry;
        var digitSum = sum % 10;
        carry = sum >= 10 ? 1 : 0;   
        s = digitSum.toString() + s;
    }
    if (carry > 0)
        s = carry + s;
    return s;
}

                    

// Solution 1
function countWords(text)
{
    var wasSeparator = true;
    var words = 0;   
    for(var c of text)
    {
        // if current character is separator then advance and
        // set that the previous character was separator
        if (isSeparator(c))
        {
            wasSeparator = true;
            continue;
        }
        // if current character is not separator
        // ... but if previous was separator...
        if (wasSeparator)
        {
            words++;
            wasSeparator = false;
        }
    }  
    return words;
}
function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?"];
    return separators.includes(c);
}
console.log(countWords(""));
console.log(countWords("            "));
console.log(countWords("JavaScript!!!   "));
console.log(countWords("     JavaScript"));
console.log(countWords("    JavaScript is cool      "));
console.log(countWords("I like to learn JavaScript with codeguppy"));

                    

// Solution 2
function countWords(text)
{
    var words = 0;   
    if (text.length > 0 && !isSeparator(text[0]))
        words++;   
    for(var i = 1; i < text.length; i++)
    {
        var currChr = text[i];
        var prevChr = text[i - 1];       
        if (!isSeparator(currChr) && isSeparator(prevChr))
        {
            words++;
        }
    }   
    return words;
}
function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?"];
    return separators.includes(c);
}
console.log(countWords(""));
console.log(countWords("            "));
console.log(countWords("JavaScript!!!   "));
console.log(countWords("     JavaScript"));
console.log(countWords("    JavaScript is cool      "));
console.log(countWords("I like to learn JavaScript with codeguppy"));

                    

console.log(captializeWords("Create a function that will capitalize the first letter of each word in a text"));
function captializeWords(text)
{
    var text2 = "";
    for(var i = 0; i < text.length; i++)
    {
        var currChr = text[i];
        var prevChr = i > 0 ? text[i - 1] : " ";
        if (!isSeparator(currChr) && isSeparator(prevChr))
        {
            currChr = currChr.toUpperCase();
        }   
        text2 += currChr;
    }
    return text2;
}
function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?"];
    return separators.includes(c);
}

                    

console.log(sumCSV("1.5, 2.3, 3.1, 4, 5.5, 6, 7, 8, 9, 10.9"));
function sumCSV(s)
{
    var ar = s.split(",");
    var sum = 0;
    for(var n of ar)
    {
        sum += parseFloat(n);
    }
    return sum;
}

                    

var text = "Create a function, that will return an array (of string), with the words inside the text";
console.log(getWords(text));
function getWords(text)
{
    let startWord = -1;
    let ar = [];
    for(let i = 0; i <= text.length; i++)
    {
        let c = i < text.length ? text[i] : " ";
        if (!isSeparator(c) && startWord < 0)
        {
            startWord = i;
        }
        if (isSeparator(c) && startWord >= 0)
        {
            let word = text.substring(startWord, i);
            ar.push(word);       
            startWord = -1;
        }
    }
    return ar;
}
function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
    return separators.includes(c);
}

                    

var data = "John;Smith;954-000-0000\nMich;Tiger;305-000-0000\nMonique;Vasquez;103-000-0000";
var ar = csvToArray(data);
console.log(JSON.stringify(ar));
function csvToArray(data)
{
    var arLines = data.split("\n");
    for(var i = 0; i < arLines.length; i++)
    {
        var arLine = arLines[i].split(";");
        arLines[i] = arLine;
    }
    return arLines;
}

                    

const string = 'hi there';

//option 1
const usingSplit = string.split('');
//option 2
const usingSpread = [...string];
//option 3
const usingArrayFrom = Array.from(string);
//option 4
const usingObjectAssign = Object.assign([], string);

console.log(usingSplit);
console.log(usingSpread);
console.log(usingArrayFrom);
console.log(usingObjectAssign);

// Result will be same for all options
// [ 'h', 'i', ' ', 't', 'h', 'e', 'r', 'e' ]

                    

console.log(getCharCodes("I like JavaScript"));
function getCharCodes(s)
{
    var ar = [];
    for(var i = 0; i < s.length; i++)
    {
        var code = s.charCodeAt(i);
        ar.push(code);
    }
    return ar;
}

                    

console.log(codesToString([73,32,108,105,107,101,32,74,97,118,97,83,99,114,105,112,116]));

function codesToString(ar)
{
    return String.fromCharCode(...ar);
}

                    

var text = "I LOVE JAVASCRIPT";
var textEnc = encrypt(text, 13);
var textDec = decrypt(textEnc, 13);

console.log(text);
console.log(textEnc);
console.log(textDec);

// Decrypt a message by using the same encrypt function
// ... but using the inverse of the key (e.g. rotate in the other direction)
function decrypt(msg, key)
{
    return encrypt(msg, key * -1);
}

// Function will implement Caesar Cipher to
// encrypt / decrypt the msg by shifting the letters
// of the message acording to the key
function encrypt(msg, key)
{
    var encMsg = "";
    for(var i = 0; i < msg.length; i++)
    {
        var code = msg.charCodeAt(i);
        // Encrypt only letters in 'A' ... 'Z' interval
        if (code >= 65 && code <= 65 + 26 - 1)
        {
            code -= 65;
            code = mod(code + key, 26);
            code += 65;
        }
        encMsg += String.fromCharCode(code);
    }
    return encMsg;
}
// Modulo function: n mod p
function mod(n, p)
{
    if ( n < 0 )
        n = p - Math.abs(n) % p;
    return n % p;
}

                    

var ar = [23, 1000, 1, -1, 8, 3];
console.log(ar);
bubbleSort(ar);
console.log(ar);

function bubbleSort(ar)
{
    var shouldSort = true;
    var length = ar.length;

    while(shouldSort)
    {
        shouldSort = false;
        length--;
        
        for(var i = 0; i < length; i++)
        {
            var a = ar[i];
            if ( a > ar[i+1] )
            {
                ar[i] = ar[i+1];
                ar[i+1] = a;
                shouldSort = true;
            }
        }
    }
}

                    

console.log(getDistance(100, 100, 400, 300));

function getDistance(x1, y1, x2, y2)
{
    var l1 = x2 - x1;
    var l2 = y2 - y1;
    
    return Math.sqrt(l1 * l1 + l2 * l2);
}

                    

console.log(collisionCircleCircle(200, 200, 100, 300, 300, 50));

function collisionCircleCircle(circle1X, circle1Y, circle1R, circle2X, circle2Y, circle2R)
{
    return getDistance(circle1X, circle1Y, circle2X, circle2Y) <= circle1R + circle2R;
}

// Calculate the distance between the two specified points
function getDistance(x1, y1, x2, y2)
{
    var l1 = x2 - x1;
    var l2 = y2 - y1;
    
    return Math.sqrt(l1 * l1 + l2 * l2);
}

                    

var ar = [ ["John", 120],
            ["Jane", 115],
            ["Thomas", 123],
            ["Mel", 112],
            ["Charley", 122]
         ];

var numbers = extractCol(ar, 1);
console.log(numbers);

function extractCol(ar, colNo)
{
    var arCol = [];
    
    for(var i = 0; i < ar.length; i++)
    {
        arCol.push(ar[i][colNo]);
    }
    
    return arCol;
}

                    

console.log(binaryToNumber("11111111"));

function binaryToNumber(sBinary)
{
    return parseInt(sBinary, 2);
}

                    

var ar = [1, 2, [15, [23], [5, 12]], [100]];

console.log(sumArray(ar));

function sumArray(ar)
{
    var sum = 0;
    
    for(var el of ar)
    {
        if (Array.isArray(el))
        {
            el = sumArray(el);
        }
        
        sum += el;
    }
    
    return sum;
}

                    

// Solution 1

var ar = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0];

var max = findMax(ar);
console.log("Max  = ", max);

// Use recursion to find the maximum numeric value in an array of arrays
function findMax(ar)
{
    var max = -Infinity;

    // Cycle through all the elements of the array
    for(var i = 0; i < ar.length; i++)
    {
        var el = ar[i];

        // If an element is of type array then invoke the same function
        // to find out the maximum element of that subarray
        if ( Array.isArray(el) )
        {
            el = findMax( el );
        }

        if ( el > max )
        {
            max = el;
        }
    }

    return max;
}

                    

// Solution 2

var ar = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0];

var max = findMax(ar);
console.log("Max  = ", max);

// Use a stack to find the maximum numeric value in an array of arrays
function findMax(arElements)
{
    var max = -Infinity;

    // This is the stack on which will put the first array and then 
    // all the other sub-arrays that we find as we traverse an array     
    var arrays = [];

    arrays.push(arElements);

    // Loop as long as are arrays added to the stack for processing
    while(arrays.length > 0)
    {
        // Extract an array from the stack
        ar = arrays.pop();
        
        // ... and loop through its elements
        for(var i = 0; i < ar.length; i++)
        {
            var el = ar[i];

            // If an element is of type array, we'll add it to stack
            // to be processed later
            if ( Array.isArray(el) )
            {
                arrays.push(el);
                continue;
            }
            
            if ( el > max )
            {
                max = el;
            }
        }
    }

    return max;
}

                    

var ar1 = [2, 4, 10, [12, 4, [100, 99], 4], [3, 2, 99], 0];
var ar2 = copyArray(ar1);

console.log(ar2);

function copyArray(ar)
{
    var ar2 = [];
    
    for(var el of ar)
    {
        if (Array.isArray(el))
        {
            el = copyArray(el);
        }
        
        ar2.push(el);
    }
    
    return ar2;
}

                    

var text = "Create a function to return the longest word(s) in a sentance.";
console.log(getLongestWords(text));
function getLongestWords(text)
{
    var words = getWords(text);  
    var maxSize = 0;
    var maxPositions = [];  
    for(var i = 0; i < words.length; i++)
    {
        var currWordSize = words[i].length;      
        if (currWordSize > maxSize)
        {
            maxSize = currWordSize;
            maxPositions = [ i ];
        }
        else if (currWordSize === maxSize)
        {
            maxPositions.push(i);
        }
    }
    return getElements(words, maxPositions);
}
// Get only the elements from specified positions from the array
function getElements(ar, arPositions)
{
    var arNew = [];  
    for(var pos of arPositions)
    {
        arNew.push(ar[pos]);
    }  
    return arNew;
}
// Returns an array with the words from specified text
function getWords(text)
{
    let startWord = -1;
    let ar = [];  
    for(let i = 0; i <= text.length; i++)
    {
        let c = i < text.length ? text[i] : " ";
        if (!isSeparator(c) && startWord < 0)
        {
            startWord = i;
        }      
        if (isSeparator(c) && startWord >= 0)
        {
            let word = text.substring(startWord, i);
            ar.push(word);          
            startWord = -1;
        }
    }
    return ar;
}
function isSeparator(c)
{
    var separators = [" ", "\t", "\n", "\r", ",", ";", ".", "!", "?", "(", ")"];
    return separators.includes(c);
}

                    

var ar = ["Shuffle", "an", "array", "of", "strings"];

console.log(shuffleArray(ar));

// Shuffle array implemented using Fisher–Yates shuffle algorithm
function shuffleArray(ar)
{
    for(var i = ar.length - 1; i > 0; i--)
    {
        var j = randomInt(0, i - 1);
        
        var t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }
    
    return ar;
}

// Get a random int between min and max (both included)
function randomInt(min, max) 
{
    return Math.floor(Math.random() * (max - min + 1) ) + min;

                    

console.log(getRandomNumbers(10));

function getRandomNumbers(n)
{
    var ar = [];
    
    for(var i = 1; i <= n; i++)
    {
        ar.push(i);
    }
    
    shuffleArray(ar);
    
    return ar;
}

// Shuffle array implemented using Fisher–Yates shuffle algorithm
function shuffleArray(ar)
{
    for(var i = ar.length - 1; i > 0; i--)
    {
        var j = randomInt(0, i - 1);
        
        var t = ar[i];
        ar[i] = ar[j];
        ar[j] = t;
    }
    
    return ar;
}

// Get a random int between min and max (both included)
function randomInt(min, max) 
{
    return Math.floor(Math.random() * (max - min + 1) ) + min;
}

                    

var ar = getCharFrequency("Find the frequency of characters inside a string");
console.log(JSON.stringify(ar));

function getCharFrequency(text)
{
    var ar = [];

    for(var chr of text)
    {
        updateFrequency(ar, chr);
    }
    
    return ar;
}

function updateFrequency(ar, chr)
{
    for(var el of ar)
    {
        if (el.chr === chr)
        {
            el.count++;
        }
    }
    
    ar.push({ chr : chr, count : 1 });
}

                    

console.log(fibonacci(500));

function fibonacci(n)
{
    if (n === 0)
        return "0";

    if (n === 1)
        return "1";

    var n1 = "0";
    var n2 = "1";

    for(var i = 2; i <= n; i++)
    {
        var sum = add(n1, n2);

        n1 = n2;
        n2 = sum;
    }

    return n2;
}

function add(sNumber1, sNumber2)
{
    var maxSize = Math.max(sNumber1.length, sNumber2.length);
    
    var s1 = sNumber1.padStart(maxSize, "0");
    var s2 = sNumber2.padStart(maxSize, "0");

    var s = "";
    var carry = 0;
    
    for(var i = maxSize - 1; i >= 0; i--)
    {
        var digit1 = parseInt(s1[i]);
        var digit2 = parseInt(s2[i]);
        
        var sum = digit1 + digit2 + carry;
        var digitSum = sum % 10;
        carry = sum >= 10 ? 1 : 0;

        s = digitSum.toString() + s;
    }
    
    if (carry > 0)
        s = carry + s;
    
    return s;
}

                    

console.log(factorial(70));

// Calculate factorial(n) ... using big number calculations
function factorial(n)
{
    var prod = "1";
    
    for(var i = 2; i <= n; i++)
    {
        prod = mult(prod, i.toString());
    }
    
    return prod;
}

// Multiplies sNumber1 * sNumber2
// Each number is provided as string
function mult(sNumber1, sNumber2)
{
    // Calculate partial results according to multiplication algorithm
    var partialResults = [];
    
    for(var i = sNumber2.length - 1; i >= 0; i--)
    {
        var digit = parseInt(sNumber2[i]);
        
        var partialResult = multDigit(sNumber1, digit);
        partialResult += "0".repeat(partialResults.length);
        
        partialResults.push(partialResult);
    }
    
    // Sum partial results to obtain the product
    var sum = "";
    
    for(var r of partialResults)
    {
        sum = add(sum, r);
    }
    
    return sum;
}

// Multiplies number sNumber (as string) with a single digit number
function multDigit(sNumber, digit)
{
    var p = "";
    var carry = 0;
    
    for(var i = sNumber.length - 1; i >= 0; i--)
    {
        var numberDigit = parseInt(sNumber[i]);
        
        var prod = digit * numberDigit + carry;
        var prodDigit = prod % 10;
        carry = Math.floor(prod / 10);
        
        p = prodDigit.toString() + p;
    }
    
    if (carry > 0)
        p = carry + p;
        
    return p;
}

function add(sNumber1, sNumber2)
{
    var maxSize = Math.max(sNumber1.length, sNumber2.length);
    
    var s1 = sNumber1.padStart(maxSize, "0");
    var s2 = sNumber2.padStart(maxSize, "0");

    var s = "";
    var carry = 0;
    
    for(var i = maxSize - 1; i >= 0; i--)
    {
        var digit1 = parseInt(s1[i]);
        var digit2 = parseInt(s2[i]);
        
        var sum = digit1 + digit2 + carry;
        var digitSum = sum % 10;
        carry = sum >= 10 ? 1 : 0;

        s = digitSum.toString() + s;
    }
    
    if (carry > 0)
        s = carry + s;
    
    return s;
}