Posts

Showing posts from June, 2022

JavaScrpt Math.max() and Math.min for Arrays

To find the max or min values from an array in JavaScriput, one does not need to reinvent the wheel, just use the native Math.max() or Math.min() methods.  Problem The problem with the native Math.max() or Math.min() methods is that they take in numbers not an array. If you put in an array, the return value is NaN. Solution The solution to this problem is to enter in the array using the dot operator. Example var arr = [1,2,3,4]; console.log(Math.max(arr)); //NaN console.log(Math.max(...arr)); //4

JavaScript Code for Randomly Select Items from An Array Without Repetition

Here is one way to select items from an array without repeting selecting the same item. Selecting items from an array with repetition should be very easy. Just keep randomly generate an array index with Math.floor(Math.random()*array.length). Logic Here is the logic behind array item selectoin without repetion: Define a function that takes 2 parameters. One is the number if items you need from an array, the oither is the original array where you want to pick items from. In the function copy the array with the dot operator. Loop the number of times matching the number of items you need. Once an item is picked, use the array.splice() method to delete that item. This is where the 2nd step is important because the original input array would be modified otherwise. Code function selectFromArrayWithoutRepetition(numberOfItems,array){ var originalArray = [...array]; var l; var arrayWithSel...

JavaScript Replace Characters in a String

To replace characters in a string in JavaScript, we can use the string.replace() methods, Assign to a new variable One thing to keep in mind is that the replace method does not change the original string. So in order to get the new string after some of its characters are replaced, we need to assign the operation to a new variable or even itself. var str = "a b c a b c"; str.replace("a",""); console.log(str); //a b c a b c which is the same as before. var newStr = str.replace("a",""); console.log(newStr); //b c a b c. The first a is gone. str = str.replace("a",""); console.log(str); //b c a b c. Assign to itself wokks, too. Differences between g and m in Regular Expression Actually, you can just use g not gm in the regular expression if you want to replace multiple characters in a string. Here \n means a line break in the string. var str = "a b c \na b c"; str = str.replace(/a/g,"...