Javascript Array Function

SPLICE

- changes the content of an array by removing existing elements and/or adding new elements.

array.splice(start, deleteCount, item1, item2, ...)

var arr = ['a','b','c','d'];

arr.splice(2, 0, "e");  // [a,b,e,c,d]

var arr1 = ['a','b', 'c', 'd'];

arr2 = arr1.splice(2, 2); // remove 2 element from index 2  
// result
 //arr=[a,b]
//arr2 = [c,d]



myarr = ['a','b','c','d','e'];

myarr1 = myarr.splice(0, 2, 'm', 'n', 'o'); // remove 2 element from index 0 and  insert m,n,o
// result
//myarr = [m,n,o,c,d,e]
//myarr1 = [a,b]

MAP


var oldArray = [1,2,3,4,5];
var newArray = oldArray.map(function(val){ return val*3;});


Reduce


- The array method reduce is used to iterate through an array and condense it into one value. 

var array = [4,5,6,7,8]; 
var singleVal = 0; 
 singleVal = array.reduce(function(previousVal, currentVal) { 
    return previousVal + currentVal; 
}, 0);


- Second param is optional initial value. ['currentVal] in this case. 
- If no initial value is specified it will be the first array element and currentVal will start with the second array element.



Filter

-The filter method is used to iterate through an array and filter out elements where a given condition is not true.
-And return array content list of element removed from original array.


var oldArray = [1,2,3,4,5];
var newArray = oldArray.filter(function(val){ return val%2==0 ;});

// this will return array with list of even number.
// old array has odd number

Sort


- Sort the values in an array alphabetically or numerically.

array = [1, 21,12, 2];

array.sort(); // sort alphabetically

array.sort(function(a, b) { return b-a; }); // sort decendin order

array.sort(function(a, b) { return a-b; }); // sort ascending order 

Reverse

array=[3,6,9];
-You can use the reverse method to reverse the elements of an array.
array.reverse();  // [9,6,3];

Concate


-Concatenate can be used to merge the contents of two arrays into one.

array1 = [1,2,3];
array2 = [7,8,9];

newArray = array1.concate(array2); // [1,2,3,7,8,9];

Split

- Split a string into an array.

str = "Hello world";
array1 = str.split(" ");   // split with space ["Hello", "world"];
array2 = str.split("");   // split nothing splits every character ['H','e','l','l','o',' '.'w','o','r','l','d'];

Join

- join array into string.

array1 = ["Hello", "world"];
str = array1.join(" "); // "Hello world"






Share this

Related Posts

Previous
Next Post »