Showing posts with label JavaScript Tutorial. Show all posts
Showing posts with label JavaScript Tutorial. Show all posts

Thursday, April 12, 2018

Important methods in Map with example

Map is like key value pair concept (like an Object). But Map allows keys as any type. Remember object allows only string key.

Note: ES6 map is different. Do not make confuse yourself.

Main methods are below,

      new Map() – creates the map.

     map.set(key, value) – stores key and value.

     map.get(key) – returns the value by the key. Suppose If key doesn’t exist undefined will be  returned.

     map.has(key) – returns true if the key exists, else false will be returned.

     map.delete(key) – removes the value by the key.

     map.clear() – clears the map.

     map.size – returns the current element count.

Simple Example I:



let map = new Map();

map.set('1', 'stringOne');   // a string key
map.set(1, 'number1');     // a numeric key
map.set(true, 'booleanValueTrue'); // a boolean key

alert( map.get(1)   ); // 'number1'
alert( map.get('1') ); // 'stringOne'
alert( map.get(true) ); // 'booleanValueTrue
alert( map.size ); // 3


Note: See the above example, Keys are not converted to string.





Array Sort - Reverse

To sort an array in reverse, we can use reverse method directly. See below example,

1. Reverse an Integer array


let arr = [1, 2, 3, 4, 5];
arr.reverse();

alert( arr ); // 5,4,3,2,1

2. Reverse an string array


var fruitsTest = ["Banana", "Orange", "Apple", "Mango"];
fruitsTest.reverse();

Note: Reverse means , just reverse( End to start) the output. not any order.

Wednesday, April 11, 2018

Array ReOrdering - Sort


        In Javascript , the items are sorted as strings by default. So if you try to sort an array with have integer value, it will return incorrect result. See below example,


let arr = [ 1, 2, 7,15, 18 ];

arr.sort();

alert( arr );  // 1,15,18,2,7(Wrong Result)

The above example returns a wrong result. Because as I said earlier, sorted by string is default.

Remember, internally it will convert as string.

1. Classical Trick


function compareNumeric(a, b) {
  if (a > b) return 1;
  if (a == b) return 0;
  if (a < b) return -1;
}

let arr = [ 1, 2, 15, 7, 19, 54, 87, 43 ];
arr.sort(compareNumeric);
alert(arr);  // 1,2,7,15,19,43,54,87

2. With simple comparison




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort(function(a, b) { return a - b; }); // Ascending

alert(arrSort);

Note: For descending use b-a.


3. Same with Arrow function




let arrSort = [ 1, 2, 15, 76, 76, 34, 89, 12 ];

arrSort.sort( (a, b) => a - b );

alert(arrSort);


Conclusion:

Here all the example is only for integer array. Suppose If you want to sort an string array, no need to worry about above logic. Simply you can call sort method directly.







Thursday, April 5, 2018

Array Reordering - map


                      This method is really very useful and often time we will use in our project.

It calls the function for each element of the array and returns the array of results. It does not change the original array.

Syntax:

let result = arr.map(function(item, index, array) {
  // returns the new value instead of item

})

item      -   The value of the current element and its mandatory.
index    -   The array index of the current element and its an optional parameter.

array    -   The array object the current element belongs to the array and its an optional.


let lengths = ["One", "Two", "Three"];
var lengthTest = lengths.map(item => item.length)
alert(lengthTest); // 3,3,5






Wednesday, April 4, 2018

Array search - Filter

We know find method looks for a single (first) element. But filter will check all passed data and return an array.

The syntax is same as find method,

let results = arr.filter(function(item, index, array) {
  ..................
});

Example:


let usersArrOfObject = [
  {id: 1, name: "John"},
  {id: 2, name: "Pete"},
  {id: 3, name: "Mary"},
  {id: 4, name: "Maths"},
  {id: 5, name: "Mercy"}
];

let outputUsers = usersArrOfObject.filter(item => item.id < 3);

alert(outputUsers.length); // 2
console.log(outputUsers);

From the above we are passing an item and checking the condition which specifies id is less than 3. So passed data as returned as array.







Array search - find and find Index for an object

Just think, You have an array of objects. How do you find an object with the specific condition in that array?

Here, the arr.find method will do the job for you!

Syntax:

let result = arr.find(function(item, index, array) {
  ..........................
});

item - It is the element.
index  - It is its index.
array  It is the array itself.


Example :


let arr = [

    { name:"string 1", value:"this", other: "that" },

    { name:"string 2", value:"this", other: "that" }

];

let obj = arr.find(o => o.name === 'string 1');

console.log(obj);

Output:
{
  "name": "string 1",
  "value": "this",
  "other": "that"
}

If found happen , returns true and the search will be stopped, the item is returned. If nothing found, undefined is returned.

From the above I have used ES6 arrow function, arr having array of objects. Here o is the parameter (current item) and its getting name from the current and checking with our condition. If its will get match, returns true and further search will be stopped.

If nothing matching undefined will be returned.

Note:
We did not use any other parameter except item , mentioned in the syntax.


arr.findIndex 

               The arr.findIndex method is also same, but it will returns the index where the element was found instead of the element.










Array search elements

Actually lot of methods there for searching in an array.we can see those all later on next chapter.

Here we are going to see the below three methods.

      1. indexOf

      2. lastIndexOf 

      3. includes

Generally indexOf function means, you would have thought its working based on characters. But java script, here not the case. Its an item in java script.

A short intro about these all function. Let see...

Syntax:
arr.indexOf(item , from)

It returns the position of the first occurrence of a specified value in a string. If unable to find will return -1.

item - Its specifies what you are searching...
from - Its Optional. Default 0. At which position to start the search(item).


Syntax:
arr.lastIndexOf(item, from)

It looks from right to left. Means, returns the position of the last occurrence of a specified value in a string. If unable to find will return -1.

item - The string(item) what you are going to search.
from - Its Optional. The position where to start the search.

Syntax:
arr.includes(item, from)

It checks whether a string contains the characters of a specified string. This method returns true if the string contains the characters, and false if not able to find.

item - The string, what you are going to search.
from - Its an optional. Default is 0. At which position to start the search(item)

Example for indexOf:
Q: Find the first occurrence e here.


var str = "Hello world, welcome to JS";
var n = str.indexOf("e");

alert(n); // 1


Q: Search e which should start position from 5.

var str = "Hello world, welcome to javascript";
var n = str.indexOf("e", 5);

alert(n); // 14


Example for lastIndexOf:


Q: Search last occurrence  "love" from the given string.


var str = "Hello I love JS much.";
var n = str.lastIndexOf("love");
alert(n) // 8

Q: Search item "love" which should start position at 30.


var str = "Hello I love JS very much very much very much";
var find = str.lastIndexOf("very", 30);
alert(find) // 26

Example for includes:


Q: Find 'world' from below given string.


var str = "Hello world, welcome JS.";
var n1 = str.includes("world");

alert(n1); // True

Q: Find 'world' from below given string.


var str = "Hello world, welcome JS.";
var n2 = str.includes("world", 12);

alert(n2); // false










Friday, March 30, 2018

Array concat method

concat method joins the array with other arrays and/or items.

The syntax is:

arr.concat(arg1, arg2...)

Explanation:

The arguments could either arrays or values. After concat the result is a new array containing items from arr, then arg1, arg2 etc.

Below is very basic example for concat.



let arr = [1, 2];

// merge arr with [3,4]
alert( arr.concat([3, 4])); // 1,2,3,4

// merge arr with [3,4] and [5,6]
alert( arr.concat([3, 4], [5, 6])); // 1,2,3,4,5,6

// merge arr with [3,4], then add values 5 and 6
alert( arr.concat([3, 4], 5, 6)); // 1,2,3,4,5,6


Adding objects is little different. It will add as a whole. Let see a example,


let arr = [1, 2];

let arrayObject = {
  0: "something",
  length: 1
};

alert( arr.concat(arrayLike) ); // 1,2,[object Object]
//[1, 2, arrayObject]







Array slice method


The syntax is:

arr.slice(start, end)

Slice method will returns a new array where it copies all items metioned from start index "start" to "end".

Both start and end can be negative, in this case position from array end is assumed.(like splice).

Below example can illustrate more...



let str = "test";
let arr = ["t", "e", "s", "t"];

alert( str.slice(1, 3) ); // es
alert( arr.slice(1, 3) ); // e,s

alert( str.slice(-2) ); // st
alert( arr.slice(-2) ); // s,t


Things To Remember:

1. Remembering the syntax make you more stronger easily in javascript.

2. Slice end will not be added while slice operation.

3. Slice will return an array always.

4. Negative index position allowed.







Array methods splice in detail


We have already seen some array methods, now we can see some other important methods.

The syntax of splice method is,

arr.splice(index[, deleteCount, elem1, ..., elemN])

index - specifying the position.

deleteCount - specifying the count of deleted elements.( don't confuse, we can see example)


1. First let start with deletion, see below example.



let arrTest = ["I", "study", "JavaScript"]; // Index start from 0

arrTest.splice(1, 1); // from index 1 remove 1(deletedcount) element

alert( arrTest ); // ["I", "JavaScript"]



2. Remove and Replace with other elements.


let spliceTest = ["I", "study", "JavaScript", "right", "now"];

spliceTest.splice(0, 3, "Let's", "dance"); // 0 is index;
                             3 - delete count ; 
                             remaining is for insert element

alert( spliceTest ) //  ["Let's", "dance", "right", "now"]


3. How to store removed array elements ?


let normalArray = ["I", "study", "JavaScript", "right", "now"];

// remove 2 first elements
let removedArrayElement = normalArray.splice(0, 2);

alert( removedArrayElement ); // "I", "study" <-- removed elements from an array

3. I do not want to remove an elements, but I need to insert with splice. How ?



let Originalarr = ["I", "study", "JavaScript"];

// from index 2
// delete 0 --> This is important point here
// then insert "complex" and "language"
Originalarr.splice(2, 0, "complex", "language");

alert( Originalarr ); // "I", "study", "complex", "language", "JavaScript"


4. Can I go ahead with negative indexes ?

Negative indexes are allowed in splice. It specify the position from the end of the array.

-1 means, one step back from end
-2 means, two step back from end and so on....


Example is below...



let arrNegativeEg = [1, 2, 5];

// from index -2 (two step from the end)
// delete 0 elements,
// then insert 3 and 4
arrNegativeEg.splice(-2, 0, 3, 4);

alert( arrNegativeEg ); // 1,3,4,2,5








Array with loop

Some types of for loop is there to iterate an array element. Let see one by one.

1. Classical for loop

2. for..of loop

3. for..in loop


Example for classical for loop.


let arrayExampleLoop = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) {
  alert( arrayExampleLoop[i] );
}


 Example for for..of loop:


let fruitsForOfLoop = ["Apple", "Orange", "Plum"];

// iterates over array elements
for (let fruit of fruitsForOfLoop) {
  alert( fruit );
}


Example for for...in loop:



let arrForInLoop = ["Apple", "Orange", "Pear"];

for (let key in arrForInLoop) {
  alert( arrForInLoop[key] ); // Apple, Orange, Pear
}

For arrays , we should not use for..in loop(performance issue) . But for objects you can go.








Array Methods


1. pop/push
2. shift/unshift

Things To Remember:

       1. push appends an element to the end.

       2. shift get an element from the beginning

       3. pop takes an element from the end. (remove)


Note:

1. Pop and Push will work with end of the array.

2. Shift and unShift work with starting of the array.



Let see an example for pop,

Below will extract the last element and returns.


let test = ["Apple", "Orange", "Grapes"];

alert( test.pop() ); // remove "Grapes"

alert( test ); // Output is : Apple, Orange


Let see an example for push,

Append the element to the end of the array


let fruit = ["Apple", "Orange"];

fruit.push("Grapes");

alert( fruit ); // Apple, Orange, Grapes


Let see an example for shift,

Extracts the first element of the array and returns it.


let fruitsTest = ["Apple", "Orange", "Pear"];

alert( fruitsTest.shift() ); // remove Apple

alert( fruitsTest ); // Orange, Pear


Let see an example for unshift,


Add the element to the beginning of the array.


let unshiftExample = ["Orange", "Pear"];

unshiftExample.unshift('Apple');

alert( unshiftExample ); // Apple, Orange, Pear


How do you add multiple elements at a single operation?

see the below example,


let fruitsMultiple = ["Apple"];

fruitsMultiple.push("Orange", "Peach");
fruitsMultiple.unshift("Pineapple", "Lemon");

// ["Pineapple", "Lemon", "Apple", "Orange", "Peach"]
alert( fruitsMultiple );









Wednesday, March 28, 2018

Arrays declaration initialization add and replace

Things to remember :

          Generally we will go arrays for ordered collection or If you want to insert a property between existing ones. Object will not support in this case. So we are choosing array here.

Array elements are numbered, starting with zero.

How do we declare it ?

Below are two possible ways to declare array in javascript. Most of the time all developers preferring to use second syntax only. 


Syntax I:
let arr = new Array();

Syntax II:
let arr = [];

Below are main while using array in your project. So remember these all always.

1. Initialization
2. Get element based on index
3. Replace element
4. Add new element
5. Find length


//Array Initialization
let terms = ["Test", "Drive", "JavaScript"];

//Get elements by index number
alert( terms[0] ); // Test
alert( terms[1] ); // Drive
alert( terms[2] ); // JavaScript

//Replace an elements
terms[2] = 'Vechicle'; // now ["Test", "Drive", "Vechicle"]

// Adding new ones
terms[3] = 'Hero'; // now ["Test", "Drive", "Vechicle", "Hero"]

// Finding length or count
alert( terms.length ); // 4

Below is the style mostly developers choose for array. Its easy to understand and very clear.


let terms = [
  "Test",
  "Drive",
  "Vechicle",
]; 






Friday, March 23, 2018

Date parse with String

The syntax for far Date.parse is ,

Date.parse(str)

You should pass string as a parameter and The string format should be: YYYY-MM-DDTHH:mm:ss.sssZ.

Explanation:

YYYY-MM-DD – is the date: year-month-day.

The character "T" is used as the delimiter.

HH:mm:ss.sss – is the time: hours, minutes, seconds and milliseconds.

Z is an optional denotes the time zone. A single letter Z that would mean UTC+0.

You can pass short like YYYY-MM-DD or YYYY or YYYY-MM also possible.



let ms = Date.parse('2018-01-21T13:45:50.417-09:00');

alert(ms);

Output: 
1516574750417


let date = new Date( Date.parse('2015-01-23T13:41:50.417-05:00') );

alert(date);
Output:
Sat Jan 24 2015 00:11:50 GMT+0530 (India Standard Time)







Accessing Date

Below are some of methods in java script to access date object.

1. getFullYear()
                            It will give the year in 4 digits. Some developers may get confuse with getYear() method. Please remember this was deprecated and sometimes it will give you two digit year. So it may lead you to provide wrong output.

2. getMonth()
                            It will give the month, means from 0 to 11.

3. getDate()
                            It will give the day of the month, from 1 to 31.

4. getHours() , getMinutes(), getSeconds() and getMilliseconds()

                           The above all will give you the corresponding time components.

5. getDay()
                           It will give day of the week and its starting from 0 (Sunday) to 6 (Saturday). Remember, the first day is always Sunday only.

6. getTime()

                           It will returns the timestamp for the date (milliseconds from the January 1st of 1970 UTC+0).








Creating Date and time

Date and Time in javascript is an in-built object.

Date Creation

There are some ways you able to create date. 

1. new Date() - No need to pass any arguments here. It will directly give the current date and time.



let now = new Date();
alert( now ); // display current date/time


2. new Date(milliseconds) - Pass milliseconds as argument.Here date calculation will be calculated after Jan 1st of 1970 UTC+0.


let Jan01_1970 = new Date(0);
alert( Jan01_1970 );

Output :
Thu Jan 01 1970 05:30:00 GMT+0530 (India Standard Time)


3. new Date(datestring) - Pass a string date here.


let date = new Date("2017-01-26");
alert(date);

Output : 
Fri Jan 26 2018 05:30:00 GMT+0530 (India Standard Time)

4. new Date(year, month, date, hours, minutes, seconds, ms) -  

The year must have 4 digits: Example 2018 2020 etc.,

The month count starts with 0 (Jan), up to 11 (Dec). Remember month starting from zero. 

The date parameter is actually the day of month, if not then 1 will be considered.

If hours/minutes/seconds/ms is absent, they could be considered as 0.



new Date(2011, 0, 1, 0, 0, 0, 0); // // 1 Jan 2011, 00:00:00
new Date(2011, 0, 1); // the same, hours etc are 0 by default







Thursday, March 22, 2018

Special Characters in Javascript

Below list of some special characters,

Character Description

\b                            Backspace
\f                            Form feed
\n                            New line
\r                            Carriage return
\t                            Tab

\uNNNN                    A unicode symbol with the hex code NNNN, for instance \u00A9 – is a
                                    unicode  the copyright symbol ©. It must be exactly 4 hex digits.

\u{NNNNNNNN}     Some rare characters are encoded with two unicode symbols, taking up to 4                                           bytes. This long unicode requires braces around it.


alert( "\u00A9" ); // It will print you copyright symbol.

alert( "\u{1F60D}" ); // It will print you smiley symbol.


All special characters should start with backslash \'.

Example I :


let specialList = "Specials:\n * One\n * Two\n * Three";

alert(specialList);
//Output: Specials:
* One
* Two
* Three



Example II :


alert( 'I\'m the World!' ); // I'm the world!

we have to prep-end the inner quote by the backslash \'. Else javascript will consider that as string end. So that we should add backslash.


Example III :


alert( `Adding backslash symbol: \\` ); // Output : Adding backslash symbol: \


To add backslash symbol in your string add lie above.





Saturday, March 10, 2018

Cloning Object in javascript

Last post , we have seen How object reference is working.But in some cases(very rare) if you want to copy exact object, means cloning, what you should do? How do you do that.

Its really a dull or tedious process.

Let see by code example,

let user = {
  name: "Kamal",
  age: 30
};

let clone = {}; // Going to clone into this empty object

// copy all properties from original into target
for (let key in user) {
  clone[key] = user[key];
}

console.log(clone);

Explanation: 

user is our original object and you have created one empty object called clone. After that , we have used for loop to iterate all the property of user object and assign the same to clone object. This loop will execute for all the properties of user. 

Checking with console log, all were copied to clone(target) object. Now you can modify your cloned object and check console. It will not affect user object. Since now cloned object is independent.

However, we have another simple way for cloning. Let see that too,

Object.assign:

Above we have used loop to iterate all the properties. So its look like some wide process. But using Object.assign() will make the process simpler.

Syntax is
Object.assign(destination[, src1, src2, src3...])

destination - Targeted object for clone
src1, src2,src3 etc., - Source object where you have to copy.

let user = { name: "Surya" };

let business = { businessType: "Cinema" };
let type = { isActor: true };

// copies all properties from business and type into user
Object.assign(user, business, type); console.log(user);

Output:
{name: "Surya", businessType: "Cinema", isActor: true}

Now everything is copied into our targeted user object.







Thursday, March 8, 2018

Objects copying by Reference

Generally, copying the object means, its not copy the exact object. Just Its copying the object reference. So exact object is different and reference is different.

We can discuss clone in next post.

Example:


let person = { name: 'Kannan', age: 21 };

let employee = person; // applied employee reference

employee.name = 'Rajni';

console.log(person.name); // Rajni

Initially person.name is Kannan but after modification by reference like employee= person, its reference will be considered and changes will reflected. please check the console log.

How do you compare ?

Once you have reference you would get a chance to check object reference. We can do it by == and === operator. However , I always use ===.



let a = {};
let b = a; // applied copy reference

alert( a == b ); // true, pointing same reference of object
alert( a === b ); // true, this also true






Wednesday, March 7, 2018

Objects with Square Brackets

Consider the below object,

let test = {
  name: "Raj",
  age: 19,
}

Here , you are going to add another one property like state and district property. If you try directly based on the last post, it will throw an error. So what the error, check below.

// syntax error will occur
test.state district = TamilNadu Chennai


To solve that, you should use square brackets.

// setting value
test["state District"] = "TamilNadu Chennai";

// getting value
console.log(test["state District"]); // 

// deleting value
delete test["state District"];

From the above, We have not used dot operator and used [] .


Another important, here you can use any reserved words like "for", "switch", "let" etc., See the below to confirm how its working.

let obj = {
  for: 3,
  switch: 2,
  return: 5
}

console.log(obj.for + obj.switch + obj.return );  // Output 10