Javascript Techniques Flashcards
Convert a number into array in JavaScript
1. Array.from() Method var myInt = 235345;
// Getting the string as a parameter // and typecasting it into an integer let myFunc = num => Number(num);
var intArr = Array.from(String(myInt), myFunc);
// Print the result array console.log(intArr);
2. .map() Method // Declare a variable and store an // integer value var num = 235345
// Here we typecasting the num // Splitting the num, so that // we got an array of strings // Then use map function to // convert the array of strings // into array of numbers
var myArr = String(num).split("").map((num)=>{ return Number(num) })
console.log(myArr)
3. using .reduce() function var myInt = 235345;
// number to string convertion var temp = ''+myInt // forming array with numbers as element var intArr = [...temp].reduce((acc, n)=> acc.concat(+n), [ ] );
// Print the result array console.log(intArr);
Use a variable in a JS RegEx
The right way of doing it is by using a regular expression constructor new RegExp().
let pattern = “\d”;
let re = new RegExp(\\b${pattern}\\b
, ‘gi’);
console.log(inputString.replace(re, “Google”));
const str = "Hello yes what are you yes doing yes" const removeStr = "yes" //variable const regex = new RegExp(removeStr,'g'); // correct way const newstr = str.replace(regex,''); // it works
In the above code, we have passed the removeStr variable as an argument to the new RegExp() constructor method.
Clone an Array
- Spread Operator (shallow copy):
numbers = [1, 2, 3];
numbersCopy = […numbers]; - For Loop (shallow copy)
numbers = [1, 2, 3];
numbersCopy = [];
for (i = 0; i < numbers.length; i++) {
numbersCopy[i] = numbers[i];
}
- While Loop (shallow copy)
numbers = [1, 2, 3];
numbersCopy = [];
i = -1;
while (++i < numbers.length) {
numbersCopy[i] = numbers[i];
- Array.map() (shallow copy)
numbers = [1, 2, 3];
double = (x) => x * 2;
numbers.map(double);
- Cloning
identity = (x) => x;
numbers.map(identity);
// [1, 2, 3] - Array Filter (shallow copy)
numbers = [1, 2, 3];
numbersCopy = numbers.filter(() => true); - Array.reduce (shallow copy)
numbers = [1, 2, 3];
numbersCopy = numbers.reduce((newArray, element) => {
newArray.push(element);
return newArray;
}, []);
- Array.slice (shallow copy)
numbers = [1, 2, 3, 4, 5];
numbersCopy = numbers.slice();
// [1, 2, 3, 4, 5] - JSON Parse and Stringify (deep copy)
nestedNumbers = [[1], [2]];
numbersCopy = JSON.parse(JSON.stringify(nestedNumbers));
numbersCopy[0].push(300);
console.log(nestedNumbers, numbersCopy);
// [[1], [2]] // [[1, 300], [2]] // These two arrays are completely separate!
- Array.concat (shallow copy)
[1, 2, 3].concat(); // [1, 2, 3]
[1, 2, 3].concat([]); // [1, 2, 3] - Array.from() (shallow copy)
numbers = [1, 2, 3];
numbersCopy = Array.from(numbers);
// [1, 2, 3]