img

You can tap to unblur the code solution.

However, we strongly recommend that you try it out yourself first in your code editor.

The sole purpose of such questions is to exercise and enhance your logical and reasoning abilities.

All the best.

Last updated on: 15th June 2023


nth ELEMENT
1.
Write a function that takes an array and a natural number 'n' as arguements. Make a new array consisting of every nth element of the input array.
Example 1
Input:
arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Output:
[2, 4, 6, 8, 10]
Example 2
Input:
arr = [4, 7, 9, 2, 5, 11, 6]
Output:
[9, 11]

Code :

function everyNthElemement(arr, n) {
    let newArr = [];
    let count = 0;

    for (i = 0; i < arr.length; i++) {
        count++;
        if (count == n) {
            newArr.push(arr[i]);
            count = 0;
        }
    }

    console.log(newArr);
}

everyNthElemement([1, 2, 3, 4, 5, 6, 7, 8, 9, 10], 2); // [ 2, 4, 6, 8, 10 ]
everyNthElemement([4, 7, 9, 2, 5, 11, 6], 3); // [ 9, 11 ]

IS PRIME
2.
Write a function that takes a natural number 'n'. Find out, whether 'n' is a prime number or not.
Example 1
Input:
n = 12
Output:
12 is not a Prime number
Example 2
Input:
n = 7
Output:
7 is a Prime number

Code :

function isPrime(n) {
    count = 0;
    for (i = 1; i <= n; i++) {
        // A prime number is only divisible by 1 and itself
        // So, if n is prime, the condition holds true only at i=1 and at i=n itself
        if (n % i == 0) {
            // Thus, if n is prime, count will always increment max to 2
            count++;
        }
    }
    if (count == 2) {
        // If count exactly equals to 2, n is a prime number
        return `${n} is a Prime number`;
    } else {
        // If count equals to anything else, n is not a prime number
        return `${n} is not a Prime number`;
    }
}

console.log(isPrime(12));
console.log(isPrime(7));

SAME VALUES
3.
Check whether all the values of an array are same or not. Return true or false accordingly.
Example 1
Input:
arr = [0, 0, 0, '0']
Output:
false
Example 2
Input:
arr = [1, 1, 1, 1]
Output:
true

Code :

function sameValues(arr) {
    for (i = 0; i < arr.length - 1; i++) {
        if (arr[i] !== arr[i + 1]) {
            return false;
        }
    }
    return true;
}

console.log(sameValues([0, 0, 0, '0'])); // false
console.log(sameValues([1, 1, 1, 1])); // true

COMMON ELEMENTS
4.
You are given two arrays. Write a function to find out the common elements amongst them.
Example 1
Input:
arr1 = [ 1, 2, 3, 4 ] ​ ​ arr2 = [ 3, 4, 5, 6 ]
Output:
[ 3, 4 ]
Example 2
Input:
arr1 = [ 7, 6, 19, '' ] ​ ​ arr2 = [ 45, '', 1, '6' ]
Output:
[ '' ]

Code :

function commonElements(arr1, arr2) {
    let result = [];
    for (i = 0; i < arr1.length; i++) {
        for (let j = 0; j < arr2.length; j++) {
            if (arr1[i] === arr2[j] && arr1[i] !== result[j]) {
                result.push(arr1[i]);
            }
        }
    }
    return console.log(result);
}

commonElements([1, 2, 3, 4], [3, 4, 5, 6]); // [ 3, 4 ]
commonElements([7, 6, 19, ''], [45, '', 1, '6']); // [ '' ]

ARRAY TO OBJECT
5.
Convert an array into an object. The array elements must become the keys for the object. And the number of occurences of those array elements must become the values for those keys.
Example 1
Input:
arr = [ 1, 1, 1, 2, 3, 3, 4, 5, 5, 5 ]
Output:
{ '1': 3, '2': 1, '3': 2, '4': 1, '5': 3 }
Example 2
Input:
[ 12, 7, 32, 8, 24, 6, 12, 0, 1, 7 ]
Output:
{ '0': 1, '1': 1, '6': 1, '7': 2, '8': 1, '12': 2, '24': 1, '32': 1 }

Code :

function arrayToObject(arr) {
    const obj = {};

    for (i = 0; i < arr.length; i++) {
        // Checks if the array element already exists inside the object as a key or not
        if (arr[i] in obj == false) {
            // If it does not exist, the array element gets added inside the object as a key with value = 1 ( since it is 1st occurence )
            obj[arr[i]] = 1;
            // The continue statement skips the following if conditions, and moves on to next iteration
            continue;
        }
        // Checks if the array element already exists inside the object as a key or not
        if (arr[i] in obj == true) {
            // If it already exists, the value of the respective key gets incremented by 1 ( since it is next occurence )
            obj[arr[i]] = obj[arr[i]] + 1;
        }
    }
    return console.log(obj);
}

arrayToObject([1, 1, 1, 2, 3, 3, 4, 5, 5, 5]);
arrayToObject([12, 7, 32, 8, 24, 6, 12, 0, 1, 7]);

TIMER
6.
Write a function that takes a natural number 'n' as an arguement. Construct a timer that counts from 'n' to zero. Display every 'nth' count with an interval of 1 second. The timer must stop after 'n' seconds and display 'Done'.
Example 1
Input:
n = 10
Output:
You should see counts starting from 10 to 1, with intervals of 1 second between them. Upon reaching 0, it should print 'Done'.
Example 2
Input:
n = 3
Output:
You should see counts starting from 3 to 1, with intervals of 1 second between them. Upon reaching 0, it should print 'Done'.

Code :

function timer(n) {
    console.log(n);
    let count = setInterval(function () {
        n--;
        if (n <= 0) {
            // Tells the timer to stop
            clearInterval(count);
            console.log('Done');
        } else {
            console.log(n);
        }
    }, 1000);
}

timer(10);

SUM OF EVEN
7.
Write a function to find the sum of all even numbers in an array.
Example 1
Input:
arr = [21, 13, 50, 7, 19, 11]
Output:
50
Example 2
Input:
arr = [2, 5, 8, 11, 14]
Output:
24

Code :

function sumOfEven(arr) {
    let sum = 0;

    for (let i = 0; i < arr.length; i++) {
        if (arr[i] % 2 === 0) {
            sum += arr[i];
        }
    }

    return console.log(sum);
}

sumOfEven([21, 13, 50, 7, 19, 11]); // 50
sumOfEven([2, 5, 8, 11, 14]); // 24

SWAP KEYS & VALUES
8.
Write a function to swap the keys and values of an object.
Example 1
Input:
obj = { x: 'a', y: 'b', z: 'c' }
Output:
{ a: 'x', b: 'y', c: 'z' }
Example 2
Input:
obj = { 1: '', '': 'three', 4: null }
Output:
{ '': '1', null: '4', three: '' }

Code :

function swap(obj) {

    // Returns an 'array of keys' of the object specified
    let arrKeys = Object.keys(obj);
    // Returns an 'array of values' of the object specified
    let arrValues = Object.values(obj);

    const resultObj = {};
    
    for (i = 0; i < arrKeys.length; i++) {
        // object[key] = value is a syntax to add key-value pairs to an object
        resultObj[arrValues[i]] = arrKeys[i];
    }

    return console.log(resultObj);
}

swap({ x: 'a', y: 'b', z: 'c' }); // { a: 'x', b: 'y', c: 'z' }
swap({ 1: '', '': 'three', 4: null }); // { '': '1', null: '4', three: '' }
img

"Embrace curiosity, unlock knowledge"

Copyright © 2023 - Some rights reserved

Made with

in INDIA