Array object
- written with square brackets
- separated by commas.
- Example :
- var cars = ["Saab", "Volvo", "BMW"];
- var cars = new Array("Saab", "Volvo", "BMW");//(not recommended, though correct)
- Access array element : var car = cars[0];
- Access array length: cars.length;
- Also used to add new item:
- cars[cars.length] = "newcar";//Appends "newcar" to cars
- avoid creation of array using new since,
- var points = new Array(40, 100);// Creates an array with two elements (40 and 100)
- var points = new Array(40);//Creates array with 40 undefined elements !!!!!
- use, var points = [];//instead
since, typeof cars; // returns object
- Array.isArray(cars);// returns true
- function isArray(x) {return x.constructor.toString().indexOf("Array")>-1;}
- cars instanceof Array // returns true
-------------------------------------------
Other operations on Array
- pop(): cars.pop();//Removes & returns last element("BMW")
- push(): cars.push("Fiat");//Adds new element at last index and returns the "size"(5) of new array
- shift(): cars.shift();//Removes & returns 1st element
- unshift(): cars.unshift("Fiat");//Adds new element at 1st index & returns the "size"(5) of new array(returns "undefined" for some browsers)
- delete():delete cars[0];//Changes 1st element in cars to undefined. hence not recommended
- splice(index2Splice,#ofelements2remove,Elements2Add):
- cars.splice(1,0,"car1","car2");//at position index 1, remove 0 elements and add the string, "car1","car2" at position index 1
- concat(array or arrays):
- var arr1= ["Cecilie", "Lone"];var arr2= ["Emil", "Tobias","Linus"];var arr3= arr1.concat(arr2);//joins arr1 and arr2var arr4= arr3.concat(arr1,arr2);//joins arr1, arr2 and arr3
- slice(sliceStartIndex,sliceEndIndex(optional)):
- cars.slice(1,0);//returns an array sliced at index
- reduceRight(method): This method is called on a array(with numbers only) in order to perform right to left addition (or) right to left subtractions as show in example below. Example:
- <p>Click the button to get the sum of the numbers in the array.</p><button onclick="myFunction()">Try it</button><p>Click the button to get the difference of the numbers in the array.</p><button onclick="myFunction2()">Try it</button><p>Sum of numbers in array: <span id="demo"></span></p><p>Sum of numbers in array: <span id="demo2"></span></p><script>var numbers = [65, 44, 12, 4];function getSum(total, num) {return total + num;}function myFunction(item) {document.getElementById("demo").innerHTML = numbers.reduceRight(getSum);}function getDiff(total, num) {return total - num;}function myFunction2(item) {document.getElementById("demo2").innerHTML = numbers.reduceRight(getDiff);}</script>
O/P:
Sum of numbers in array: 125
Sum of numbers in array: -117
- reduceRight(method):Does the exact same thing as reduceRight, only change is .. here its from left to right.
- copyWithin(replaceAtIndex,indexOfElementToBeReplacedWith): Replaces the element at index "replaceAtIndex" with element at index "indexOfElementToBeReplacedWith". Example:
- var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);Banana,Orange,Banana,Orange
O/P:
- array.every(functionToCheckWithEveryArrayElement): Replaces the element at index "replaceAtIndex" with element at index "indexOfElementToBeReplacedWith". Example:
- <p>Click the button to check if every element in the array has a value above a specific number.</p>
<p>Min age: <input type="number" id="ageToCheck" value="18"></p>
<button onclick="myFunction()">Try it</button>
<p>All ages above minimum? <span id="demo"></span></p>
<script>
var ages = [32, 33, 12, 40];
function checkAdult(age) {
return age >= document.getElementById("ageToCheck").value;
}
function myFunction() {
document.getElementById("demo").innerHTML = ages.every(checkAdult);
}
</script>
O/P:Minimum age:
All ages above minimum? true
- array.fill("stringToFillWith):
- var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.fill("Kiwi");
O/P: Kiwi,Kiwi,Kiwi,Kiwi
- array.map(operationToperformOneachArrayElemet):
- var numbers = [4, 9, 16, 25];
function myFunction() {
x = document.getElementById("demo")
x.innerHTML = numbers.map(Math.sqrt);
}O/P: 2,3,4,5
Note: For more Array methods, refer link.
-------------------------------------------
Sort operations on Array
- sort(): cars.sort(); // Sorts elements in alphabetical order
- sort() with array of numbers: Since in sorts only string, if an array of integers are passed for sorting. if numbers are sorted as strings, "25" > "100", because "2" is bigger than "1". Hence, we need to use a compare() function defined below:
- points.sort(function(a, b){return a - b});// sort in ascending order
- points.sort(function(a, b){return b - a});// sort in descending order
- When the sort() function compares two values, it sends the values to the compare function, and sorts the values according to the returned (negative, zero, positive) value.
- if -ve returned, a<b
- if +ve returned, a>b, so a swap occurs
- if 0 returned, a=b, so order retains.
compare() function:
- function(a, b){return a - b}//Ascending--(a)
- function(a, b){return b - a}//descending--(b)
Using compare function:
- using (a) we can find the highest value on an array
- cars.sort(function(a, b){return a - b}); cars[0];//highest value
- using (b) we can find the lowest value on an array
- cars.sort(function(a, b){return b - a}); cars[0];//lowest value
- using compare function we can sort() an Object array (wrt Integer properties)
- var cars = [
{type:"Volvo", year:2016},
{type:"Saab", year:2001},
{type:"BMW", year:2010}]; - cars.sort(function(a, b){return a.year - b.year});//sorting wrt year in ascending order.
- using compare function we can sort() an Object array (wrt String properties)
- cars.sort(function(a, b){
var x = a.type.toLowerCase();
var y = b.type.toLowerCase();
if (x < y) {return -1;}
if (x > y) {return 1;}
return 0;
});//sorting wrt String properties in ascending order.
-------------------------------------------
Array Properties
- constructor : Returns the function that created the Array object's prototype.
- var fruits = ["Banana", "Orange", "Apple", "Mango"];
- fruits.constructor;
- O/P: function Array() { [native code] }
- length : Sets or returns the number of elements in an array
- var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; - O/P: 4
- prototype : Allows you to add properties and methods to an Array object
Example
Make a new array method that transforms array values into upper case:Array.prototype.myUcase = function() {
for (i = 0; i < this.length; i++) {
this[i] = this[i].toUpperCase();
}
};myUcase method:var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.myUcase();O/P:BANANA,ORANGE,APPLE,MANGO
-------------------------------------------
No comments:
Post a Comment