Convenient and useful techniques to reduce the lines of code and pace up your Dev Work!
1. DECLARE AND INITIALIZE ARRAYS
We can initialize array of particular size with default values like “”, null or 0. You might have used these for the 1-D array but how about initializing 2-D array/matrix?
2. SORTING ARRAY OF STRING, NUMBERS OR OBJECTS
We have inbuilt methods sort() and reverse() for sorting strings but How about numbers or array of objects?
Let’s check out sorting hacks for Numbers and Objects in Increasing and Decreasing order as well.
3. EASY EXCHANGE VARIABLES
You probably swap the two variables using a third variable temp. But this tip will show you a new way to exchange variables using destructuring.
4. GET A RANDOM ITEM FROM AN ARRAY
5. GET A RANDOM NUMBER IN A SPECIFIC RANGE
This code snippet can be useful when trying to generate fake data for testing purposes, such as a salary between min and max.
6. GENERATE AN ARRAY OF NUMBERS WITH NUMBERS FROM 0 TO MAX
7. FILTER UNIQUE VALUES
The Set object type was introduced in ES6, and along with …, the ‘spread’ operator, we can use it to create a new array with only the unique values.
Before ES6, isolating unique values would involve a lot more code than that!
This trick works for arrays containing primitive types: undefined, null, boolean, string and number . (If you had an array containing objects, functions or additional arrays, you’d need a different approach!)
8. A STRING TRIM FUNCTION
9. APPEND AN ARRAY TO ANOTHER ARRAY
10. REMOVE DUPLICATES
You probably encounter an array with duplicate data and use a loop way to get rid of these duplicates. This tip will help you remove duplicates in an easy way without using any loop.
11. ROUNDING NUMBER TO N DECIMAL PLACE
12. CONVERT DECIMAL TO BINARY OR HEXA
We can use some in-built methods like .toPrecision() or .toFixed() to achieve many functionalities while solving problems.
13. GET THE LAST ITEM(S) IN AN ARRAY
The array method slice() can take negative integers, and if provided it will take values from the end of the array.
14. MAKE ARRAY EMPTY
15. USING STRING REPLACE FUNCTION TO REPLACE ALL THE VALUES
ABOUT NETTYFY TECHNOLOGIES