Remove Words from String if Included in Array in JavaScript

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

801 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

216 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

258 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

Add a Character to the Beginning of Every Word in a String in JavaScript

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

898 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

Remove Duplicates from an Array of Objects in JavaScript

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

679 Views

We are required to write a function that removes duplicate objects from an array and returns a new one. Consider one object the duplicate of other if they both have same number of keys, same keys and same value for each key.Let’s write the code for this −We will use a map to store distinct objects in stringified form and once we see a duplicate key we omit it otherwise we push the object into the new array −Exampleconst arr = [    {       "timestamp": 564328370007,       "message": "It will rain today"    },   ... Read More

Replace a Letter with Its Alphabet Position in JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:13:55

1K+ Views

We are required to write a function that takes in a string, trims it off any whitespaces, converts it to lowercase and returns an array of numbers describing corresponding characters positions in the english alphabets, any whitespace or special character within the string should be ignored.For example −Input → ‘Hello world!’ Output → [8, 5, 12, 12, 15, 23, 15, 18, 12, 4]The code for this will be −Exampleconst str = 'Hello world!'; const mapString = (str) => {    const mappedArray = [];    str    .trim()    .toLowerCase()    .split("")    .forEach(char => {       const ascii = char.charCodeAt();       if(ascii >= 97 && ascii

Find Maximum Slice of Array in JavaScript

AmitDiwan
Updated on 20-Aug-2020 06:12:36

232 Views

Let’s say, we are required to write a function that takes an array as input and returns the maximum slice of the array which contains no more than two different numbers. If we closely examine this problem this involves checking for a stable sub array and iterating over the original array.Therefore, the sliding window algorithm is very suitable for this. The code for solving this problem via sliding window algorithm will be −Exampleconst arr = [1, 1, 1, 2, 2, 2, 1, 1, 2, 2, 6, 2, 1, 8, 1, 1 ,1 ,1, 8, 1, 1, 8, 8]; const map ... Read More

Compare Two String Arrays Case Insensitive in JavaScript ES6

AmitDiwan
Updated on 20-Aug-2020 06:07:54

793 Views

We are required to write a function, say isEqual() that takes in two strings as argument and checks if they both contains the same characters independent of their order and case.For example −const first = 'Aavsg'; const second = 'VSAAg'; isEqual(first, second); //trueMethod: 1 Using arraysIn this method we convert the strings into arrays, make use of the Array.prototype.sort() method, convert them back into strings and check for equality.The code for this will be −Exampleconst first = 'Aavsg'; const second = 'VSAAg'; const stringSort = function(){    return this.split("").sort().join(""); } String.prototype.sort = stringSort; const isEqual = (first, second) => first.toLowerCase().sort() ... Read More

Sort Array Based on Presence of Fields in Objects JavaScript

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

284 Views

Let’s say we have the following array of objects −const people = [{    firstName: 'Ram',    id: 301 }, {    firstName: 'Shyam',    lastName: 'Singh',    id: 1016 }, {    firstName: 'Dinesh',    lastName: 'Lamba',    id: 231 }, {    id: 341 }, {    firstName: 'Karan',    lastName: 'Malhotra',    id: 441 }, {    id: 8881 }, {    firstName: 'Vivek',    id: 301 }];We are required to sort this array so that the object with both firstName and lastName property appears first then the objects with firstName or lastName and lastly the objects ... Read More

Find All Subarrays with Sum Equal to Number using Sliding Window Algorithm in JavaScript

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

620 Views

We are given an array of numbers and a number; our job is to write a function that returns an array of all the sub arrays which add up to the number provided as second argument.For example −const arr = [23, 5, 1, 34, 12, 67, 9, 31, 6, 7, 27]; const sum = 40; console.log(requiredSum(arr, sum));Should output the following array −[ [ 5, 1, 34 ], [ 9, 31 ], [ 6, 7, 27 ] ]Because each of these 3 sub arrays add up to 40.The Sliding Window Algorithm (Linear Time)This algorithm is mostly used when we are required ... Read More

Advertisements