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",
]; 






Tuesday, March 27, 2018

Convert HashMap To ArrayList


1. a) Convert HashMap Keys Into ArrayList :

             We should use keySet() method of HashMap which will returns the Set containing all keys of the HashMap. After that, we should pass those while creating ArrayList.


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class HelloWorld{

     public static void main(String []args){
        //Creating a HashMap object
         
HashMap<String, String> map = new HashMap<String, String>();
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
 
//Getting Set of keys from HashMap
         
Set<String> keySet = map.keySet();
         
//Creating an ArrayList of keys by passing the keySet
         
ArrayList<String> listOfKeys = new ArrayList<String>(keySet);
System.out.println("output is :" + listOfKeys);
     }
}

output is : [1, 2, 3, 4]


b) Convert HashMap Values Into ArrayList :

           We should use values() method of HashMap which will returns all values of the HashMap. After that, we should use this to create the ArrayList. let see an example below.


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class HelloWorld{

     public static void main(String []args){

//Creating a HashMap object
         
HashMap<String, String> map = new HashMap<String, String>();
 
map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
map.put("5", "Five");
//Getting Collection of values from HashMap
         
Collection<String> values = map.values();
         
//Creating an ArrayList of values
         
ArrayList<String> listOfValues = new ArrayList<String>(values);

System.out.println("output is " + listOfValues);
     }
}

output is : [One, Two, Three, Four, Five]



c) Convert HashMap Key-Value Pairs into ArrayList :

          We should use entrySet() method of HashMap which will returns the Set of Entry<K, V> objects where each Entry object represents one key-value pair. After that, We should pass this Set to ArrayList. let see below an example.


import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map.Entry;
import java.util.Set;

public class HelloWorld{

     public static void main(String []args){

HashMap<String, String> map = new HashMap<String, String>();

map.put("1", "One");
map.put("2", "Two");
map.put("3", "Three");
map.put("4", "Four");
map.put("5", "Five");

//Getting the Set of entries
         
Set<Entry<String, String>> entrySet = map.entrySet();
         
//Creating an ArrayList Of Entry objects
         
ArrayList<Entry<String, String>> listOfEntry = new ArrayList<Entry<String,String>>(entrySet);

System.out.println("output is " + listOfEntry);
     }
}

output is : [1=One, 2=Two, 3=Three, 4=Four, 5=Five]