Java script programming is client side scripting language. If you are doing lot of java script programming. very useful java script function and tricks.
1.Use the map() function method to loop through an array value
var squares = [1,2,3,4].map(function (val) {
return val * val;
});
// squares will be equal to [1, 4, 9, 16]
2.Converting JavaScript Array to Comma Separated Value (CSV)
You have a java script array of string or number value and you want to convert it to comma separated values(csv).
Example Code:
var arrayval = ['cat', 'apple', 'oranges', 'chares'];
var string = arrayval .valueOf();
//print string: cat,apple,oranges,chares
The valueOf() method will convert an array in javascript to a comma separated string.
3.Rounding number to N decimal place
var num =5.72121756
num = num.toFixed(4); // num will be equal to 5.7212
4.Remove Array element by Index
function removeByIndex(arr, index) {
arr.splice(index, 1);
}
test = new Array();
test[0] = 'Cat';
test[1] = 'Ball';
test[2] = 'bird';
test[3] = 'penguen';
alert("Array before removing elements: "+test);
removeByIndex(test, 2);
alert("Array after removing elements: "+test);
5.Comma operator
var a = 0;
var b = ( a++, 99 );
console.log(a); // a will be equal to 1
console.log(b); // b is equal to 99
6. Generate Random number from 1 to N
//random number from 1 to N
var random = Math.floor(Math.random() * N + 1);
//random number from 1 to 10
var random = Math.floor(Math.random() * 10 + 1);
//random number from 1 to 100
var random = Math.floor(Math.random() * 100 + 1);
7.Listbox Select All/Deselect All using JavaScript
function listboxSelectDeselect(listID, isSelect) {
var listboxs = document.getElementById(listID);
for(var count=0; count < listboxs.options.length; count++) {
listboxs.options[count].selected = isSelect;
}
}
8.Remove Duplicates from JavaScript Array
function removeDuplicates(arr) {
var temp = {};
for (var i = 0; i < arr.length; i++)
temp[arr[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
}
//Usage
var fruits = ['apple', 'orange', 'peach', 'apple', 'orange'];
var uniquefruits = removeDuplicates(fruits);
//print uniquefruits ['apple', 'orange', 'peach''];
9. Encode a URL in JavaScript
var encodeurl=
"http://example.com/index.html?url=" + encodeURIComponent(myUrl);
10.Serialization and deserialization (working with JSON)
var person = {name :'dev', age : 15, department : {ID : 21, name : "R&D"} };
var stringFromPerson = JSON.stringify(person);
/* stringFromPerson is equal to "{"name":"Sachine","age":31,"department":{"ID":21,"name":"R&D"}}" */
var personFromString = JSON.parse(stringFromPerson);
/* personFromString is equal to person object */