Coding hacks in Nodejs
Things you might have missed while learning javascript
1) Magic with Arrays:
In place Array Sorting.
Array.sort() → The deadliest sort.
Note: By default, the sort method sorts elements alphabetically.
Try this:
var array = [1, 2, 3, 4, 5, 6, 7, 8];
console.log(array.sort()); //Output => [1, 2, 3, 4, 5, 6, 7, 8]
var array = [11, 2, 3, 4, 5, 6, 7, 8];
console.log(array.sort());//Output => [11, 2, 3, 4, 5, 6, 7, 8]
How to do sorting of Numbers in array?
array.sort((x, y) => x — y);
2) Use of Array.reduce
To know more about reduce
2.1) To find the biggest number in an array
var array = [10, 2, -30, 4, 55, 6, 7, 8];
console.log(array.reduce((x, y) => x > y ? x : y));
2.2) To find the sum of an array
var array = [10, 2, -30, 4, 55, 6, 7, 8];
console.log(array.reduce((x, y) => x +y));
2.3) To find a number in an array greter than a given number
var array = [10, 2, -30, 4, 550, 6, 7, 8];
console.log(array.reduce(((x, y) => x > y ? x : y), 100));
In the above code,given number is 100 and the output will be 550.
If the array doesn’t have a greater value than 100, it will give 100 as output.
3) String to Array conversions
var testData = `5725 1
7712 1
2083 1
4085 1
1479 1
4627 1`;
I want to convert this testData to a javascript array.
var temp = testData.split(‘\n’);
var input = [];
temp.forEach(element => {
element = element.replace(‘ ‘, ‘,’);
element = ‘[‘ + element + ‘]’;
input.push(JSON.parse(element));
});
4) Copying an Array
var source = [1, 2, 3, 5, 6];
var destination = […source];
5) Copying an Object
var source = { a: { b: 5 } };
var destination = {…source };
Note: The spread operator … does only shallow copy.
6) in Operator
var car = {make: ‘Honda’, model: ‘Accord’, year: 1998};
console.log(‘make’ in car); //Output=> true
To check if a particular index in present
var source = [1, 2, 3, 4, 5, 7];
console.log(`${0}` in source); //Output=> true
7) Array.isArray
alert(Array.isArray({})); // Output=>false
alert(Array.isArray([])); // Output=>true
8) Unary Operator +
var result = +”3" + 3; // Output=> 6
9) Find unique letters in a String
let temp=new Set(‘abcaacb’);
console.log([…temp]); // Output=> [“a”, “b”, “c”]
10) Store unique strings in array
let temp=new Set();
temp.add(‘arun’);
temp.add(‘arun’);
temp.add(‘arun2’);
console.log([…temp]); // Output=> [“arun”, “arun2”]
11) Switch with OR conditions
switch (isNaN(x) || x)
{
case -1: counter[0]++;
break;
case true: counter[1]++;
break;
case 1: counter[2]++;
break;
}