Saturday, August 22, 2015

JavaScript Array Methods

1. Array Methods


returned valuearray methods
a string array.join([separator])
the array itself array.reverse()
the array itself array.sort([function])
a new array array.concat(value1[, value2[, ...]])
a new array array.slice(startIndex[,endIndex])
deleted elements array array.splice(startIndex, deleteCount[, value1[, value2[, ...]]])
the new length array.push(value1[, value2[, ...]])
the last element array.pop()
the new length array.unshift(value1[, value2[, ...]])
the first element array.shift()
a string array.toString()
a string array.toLocaleString()
Array.prototype.join()
string = array.join([separator])
The join() method concatenates all the elements of an array into a string and returns the resulting string.
If no separator string is specified, a comma is used.
var array = ["one", "two", "three"];

console.log(array.join()); // -> 'one,two,three'
console.log(array.join("-")); // -> 'one-two-three'
console.log(array.join(" ")); // -> 'one two three'
Array.prototype.reverse()
array.reverse()
The reverse() method reverses the order of the elements of an array and returns the array.
It modifies the array in-place and returns the modified array
var array = ["one", "two", "three"];
array.reverse(); // elements order is reversed
console.log(array); // ["three", "two", "one"]
Array.prototype.sort()
array.sort([function])
- The sort() method sorts an array elements in alphabetical order.
- It modifies the array in-place and returns the modified array.
- You can sort into some order other than alphabetical by passing a comparison function as an argument to sort()

var array = ["Zimbabwe", "Denmark", "canada", "America"];
array.sort();
console.log(array); // ["America", "Denmark", "Zimbabwe", "canada"]
You can sort in other orders by passing a comparison function as an argument to sort().
var array = ["Zimbabwe", "Denmark", "canada", "America"];
array.sort(function(a,b){
                if (a.toUpperCase() < b.toUpperCase()) 
                    return -1;
                if (a.toUpperCase() > b.toUpperCase()) 
                    return 1;
                return 0;
            });
console.log(array); // ["America", "canada", "Denmark", "Zimbabwe"]
Note the use of an unnamed function expression.
Array.prototype.concat()
newArray = array.concat(value1[, value2[, ...]]);
- The concat() method creates a new array containing the elements of the array on which is called and the values provided as arguments
- It returns the new array
var array = ["one", "two", "three"];
var new_array = array.concat("4", "5");
console.log(new_array); // ["one", "two", "three", "4", "5"]     
If the argument to concat() is an array, its elements are concatenated to the array, not the array.
var array = ["one", "two", "three"];
var new_array = array.concat(["4", "5"],["6", "7"]);    
console.log(new_array); // ["one", "two", "three", "4", "5", "6", "7"]
Array.prototype.slice()
sub_array = slice(begin[,end]);
- The slice() method creates a new array that is a subarray of the specified array.
- It returns a new array
- The begin parameter specifies the index from which to start copying elements
- The end parameter specifies the index at which to end, the end element is not included. When end is omitted, this means to copy until array.length
- A negative index as argument means to start counting from the end of the array.

var arr = ["one", "two", "three", "four", "five", "six"];
    
var new_array = arr.slice(0,3); // begin is 0, end is 3
console.log(new_array); // ["one", "two", "three"]
    
new_array = arr.slice(3); // if end is omitted it means the last element
console.log(new_array); // ["four", "five", "six"] 
    
new_array = arr.slice(1,-1); // begin is 1, end is the last element
console.log(new_array); // ["two", "three", "four", "five"]
    
new_array = arr.slice(-2,-1); // begin is the second-last, end is the last
console.log(new_array); // ["five"]
Array.prototype.splice()
deletedElementsArray = array.splice(start, deleteCount[, item1[, item2[, ...]]])
- The splice() method can remove elements from an array, add elements into an array or do both actions at a time.
- It modifies the array in-place
- It returns an array of the deleted elements.
- The deleteCount parameter indicates the number of array elements to be removed. When this parameter is omitted, this means all elements from start index through the end of the array are to be deleted.
- The item1, item2, ... parameters are the elements to be added to the array. If omitted splice will only remove elements.

var array = ["one", "two", "three", "four", "five", "six"];
var deleted = array.splice(4); 
console.log(deleted); // ["five", "six"]
console.log(array); // ["one", "two", "three", "four"]
var array = ["one", "two", "three", "four", "five", "six"];
var deleted = array.splice(2, 2, "3", "4"); 
console.log(deleted); // ["three", "four"]
console.log(array); // ["one", "two", "3", "4", "five", "six"] 
Stack methods: Array.prototype.push() and Array.prototype.pop()
length = array.push(value1[, value2[, ...]])
last_element = array.pop()
- The push() method adds one or more elements to the end of an array and returns the new length of the array.
- The pop() method removes the last element from an array and returns that element.
- They both modify the array in-place.
- Push() and pop() methods add and remove elements at the end of an array, so they allow you to implement a first-in, last-out stack

var array = [];
console.log(array.push(1,2,"three")); // 3 - the new length
console.log(array); // [1,2,"three"]
console.log(array.pop()); // "three" - the removed element
console.log(array); // [1,2]    
console.log(array.push(3)); // 3 - the new length
console.log(array); // [1, 2, 3] 
A stack is known as a Last-In-First-Out (LIFO) structure, meaning that the most recently added item is the first one removed. The methods push() and pop() allow you to handle a JavaScript array as stack
Array.prototype.unshift() and Array.prototype.shift()
length = array.unshift(value1[, value2[, ...]])
first_element = array.shift()
- The unshift() method adds one or more elements to the beginning of the array and returns the new length of the array. It shifts all existing array's elements to right by increasing their indexes.
- The shift() method removes the first element from an array and returns that element. It shifts all existing array's elements to left by decreasing their indexes.
var array = [];
console.log(array.unshift("one")); // 1 - the new length
console.log(array.unshift("two")); // 2 - the new length
console.log(array.unshift("three")); // 3 - the new length
console.log(array); // ["three", "two", "one"]
console.log(array.shift()); // "three" 
The unshift() and shift() methods insert and remove elements from the beginning of an array, while push() and pop() insert and remove elements from the end of an array.
Note: a queue adds items to the end of a list and retrieves items from the front of a list. A queue is known as First-In-First-Out (FIFO) data structure. Using shift() and push() methods allows arrays to be used as queues.
Array.prototype.toString()
string = array.toString()
- The Array object overrides the toString method of Object.
- The toString method converts each element to a string, joins the array and returns one string containing each array element separated by commas.
console.log([1,2,3].toString()); // '1,2,3'
console.log(["a", "b", "c"].toString()); // 'a,b,c'
console.log([1, [2,'c']].toString()); // '1,2,c'

console.log(["a", "b", "c"].toLocaleString()); // 'a,b,c'
Note that toString() returns the same string produced by the join() method when is invoked with no arguments.

No comments :

Post a Comment