Found 9306 Articles for Object Oriented Programming

Randomize color by number in JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:28:08

98 Views

We are required to write a function that returns a random hex color. So here is the code for doing so −Exampleconst generateRandomColor = () => {    const keys = '0123456789ABCDEF';    let color = '';    while(color.length < 6){       const random = Math.floor(Math.random() * 16);       color += keys[random];    };    return `#${color}`; }; console.log(generateRandomColor()); console.log(generateRandomColor()); console.log(generateRandomColor()); console.log(generateRandomColor());OutputThe output in the console will be −#C83343 #D9AAF3 #9D55CC #28AE22

Sum is to be calculated for the numbers in between the array's max and min value JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:27:00

116 Views

We are required to write a function, say sumBetween() that takes in an array [a,b] of two elements and returns the sum of all the elements between a and b including a and b.For example −[4, 7] = 4+5+6+7 = 22 [10, 6] = 10+9+8+7+6 = 40Let’s write the code for this function −Exampleconst arr = [10, 60]; const sumUpto = (n) => (n*(n+1))/2; const sumBetween = (array) => {    if(array.length !== 2){       return -1;    }    const [a, b] = array;    return sumUpto(Math.max(a, b)) - sumUpto(Math.min(a, b)) + Math.min(a,b); }; console.log(sumBetween(arr)); console.log(sumBetween([4, 9]));OutputThe output in the console will be −1785 39

Recursion in array to find odd numbers and push to new variable JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:25:26

350 Views

We are required to write a recursive function, say pushRecursively(), which takes in an array of numbers and returns an object containing odd and even properties where odd is an array of odd numbers from input array and even an array of even numbers from input array. This has to be done using recursion and no type of loop method should be used.Exampleconst arr = [12, 4365, 76, 43, 76, 98, 5, 31, 4]; const pushRecursively = (arr, len = 0, odd = [], even = []) => {    if(len < arr.length){       arr[len] % 2 === ... Read More

Find first repeating character using JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:24:20

570 Views

We have an array of string / number literals that may/may not contain repeating characters. Our job is to write a function that takes in the array and returns the index of the first repeating character. If the array contains no repeating characters, we should return -1.So, let’s write the code for this function. We will iterate over the array using a for loop and use a map to store distinct characters as key and their index as value, if during iteration we encounter a repeating key we return its index otherwise at the end of the loop we return ... Read More

How can I convert 'HH:MM:SS ' format to seconds in JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:23:26

226 Views

We are required to write a function that takes in a ‘HH:MM:SS’ string and returns the number of seconds. For example −countSeconds(‘12:00:00’) //43200 countSeconds(‘00:30:10’) //1810Let’s write the code for this. We will split the string, convert the array of strings into an array of numbers and return the appropriate number of seconds.The full code for this will be −Exampleconst timeString = '23:54:43'; const other = '12:30:00'; const withoutSeconds = '10:30'; const countSeconds = (str) => {    const [hh = '0', mm = '0', ss = '0'] = (str || '0:0:0').split(':');    const hour = parseInt(hh, 10) || 0;   ... Read More

Compress array to group consecutive elements JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:22:33

251 Views

We are given a string that contains some repeating words separated by dash (-) like this −const str = 'monday-sunday-tuesday-tuesday-sunday-sunday-monday-mondaymonday';Now our job is to write a function that returns an array of objects, where each object contains two properties value and count, value is the word in the string (Monday, Tuesday, Sunday) and count is their consecutive appearance count.Like for the above string, this array would look something like this −const arr = [{    val: 'monday',    count: 1 }, {    val: 'sunday',    count: 1 }, {    val: 'tuesday',    count: 2 }, {    val: ... Read More

If string includes words in array, remove them JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:20:58

656 Views

We are given a string and an array of strings; our job is to write a function that removes all the substrings that are present in the array from the string.These substrings are complete words so we are also supposed to remove leading or trailing whitespace so that no two whitespaces appear together.Therefore, let’s write the code for this function −Exampleconst string = "The weather in Delhi today is very similar to the weather in Mumbai"; const words = [    'shimla', 'rain', 'weather', 'Mumbai', 'Pune', 'Delhi', 'tomorrow', 'today', 'yesterday' ]; const removeWords = (str, arr) => {    return ... Read More

Find average of each array within an array JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:19:40

138 Views

We are required to write a function getAverage() that accepts an array of arrays of numbers and we are required to return a new array of numbers that contains the average of corresponding subarrays.Let’s write the code for this. We will map over the original array, reducing the subarray to their averages like this −Exampleconst arr = [[1,54,65,432,7,43,43, 54], [2,3], [4,5,6,7]]; const secondArr = [[545,65,5,7], [0,0,0,0], []]; const getAverage = (arr) => {    const averageArray = arr.map(sub => {       const { length } = sub;       return sub.reduce((acc, val) => acc + (val/length), 0);    });    return averageArray; } console.log(getAverage(arr)); console.log(getAverage(secondArr));OutputThe output in the console will be −[ 87.375, 2.5, 5.5 ] [ 155.5, 0, 0 ]

How to get only the first n% of an array in JavaScript?

AmitDiwan
Updated on 20-Aug-2020 06:19:16

175 Views

We are required to write a function that takes in an array arr and a number n between 0 and 100 (both inclusive) and returns the n% part of the array. Like if the second argument is 0, we should expect an empty array, complete array if it’s 100, half if 50, like that.And if the second argument is not provided it should default to 50. Therefore, the code for this will be −Exampleconst numbers = [3, 6, 8, 6, 8, 4, 26, 8, 7, 4, 23, 65, 87, 98, 54, 32, 57, 87]; const byPercent = (arr, n = ... Read More

How to add a character to the beginning of every word in a string in JavaScript?

AmitDiwan
Updated on 20-Aug-2020 06:17:16

763 Views

We are required to write a function that takes in two strings, we have to return a new string which is just the same as the first of the two arguments but have second argument prepended to its every word.For example −Input → ‘hello stranger, how are you’, ‘@@’ Output → ‘@@hello @@stranger, @@how @@are @@you’If second argument is not provided, take ‘#’ as default.Exampleconst str = 'hello stranger, how are you'; const prependString = (str, text = '#') => {    return str    .split(" ")    .map(word => `${text}${word}`)       .join(" "); }; console.log(prependString(str)); console.log(prependString(str, '43'));OutputThe ... Read More

Advertisements