Split JavaScript String by Given Array Element

AmitDiwan
Updated on 20-Aug-2020 06:31:10

179 Views

Let’s say, we are given a string and an array. Our job is to split the string according to the corresponding elements of the array. For example −Inputconst string = 'Javascript splitting string by given array element'; const arr = [2, 4, 5, 1, 3, 1, 2, 3, 7, 2];Output['Ja', 'vasc', 'ript ', 's', 'pli', 't', 'ti', 'ng ', 'string ', 'by']Let’s write a function, say splitAtPosition that takes in the string and the array and makes use of the Array.Prototype.reduce() method to return the splitted array.The code for this function will be −Exampleconst string = 'Javascript splitting string by ... Read More

Randomize Color by Number in JavaScript

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

145 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

Calculate Sum Between Max and Min Values in Array using JavaScript

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

157 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 in JavaScript

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

446 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

672 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

Convert HH:MM:SS Format to Seconds in JavaScript

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

338 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 in JavaScript

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

373 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

Remove Words from String if Included in Array in JavaScript

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

786 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 in JavaScript

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

209 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 ]

Get Only the First N Elements of an Array in JavaScript

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

244 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

Advertisements