Arrays
Arrays are list-like objects. They are just single objects that contain multiple values stored in a list.
var array = [1, 2, 3, 4, 5];
Properties of Arrays
- length: Returns the number of elements in the array.
array.length // returns 5
- constructor: Returns the constructor function for the object.
array.constructor; // returns the array constructor
- prototype: Add properties and elements to an array object.
array.prototype; // refers to array object itself
Important Methods
- push(): Add an element at the end of the array.
array.push("10"); // [1, 2, 3, 4, 5, 10]
- pop(): Remove an element from the end of the array.
array.pop(); // 10
- shift(): Remove the first element and return it.
array.shift(); // 1
- unshift(): Add an element to the beginning of an array and return length.
array.unshift(0); // 5
- concat(): Join two arrays together and return a copy of the joined array.
array2 = [99, 100];
array.concat(array2); // 0, 2, 3, 4, 5, 99, 100
- find(): Find the first element in an array that satisfies a condition.
array.find(function satisfy(num) {
return num>4; // 5
});
- sort(): Sort the array.
array.sort(function(a, b){return a-b}); // 0, 2, 3, 4 ,5, 99, 100
- filter(): Make a new array from an existing one after satisfying a condition.
array.filter(function satisfy(num) {
return num>4; // 5, 99, 100
});
- forEach(): calls a function for every element in the array.
var array = [0,2,3,4,5,99,100];
var array2 = [];
array.forEach(function mult(num) {
array2.push(num*num);
});
array2; // [ 0, 4, 9, 16, 25, 9801, 10000 ]
- map(): Creates a new array with results of a function called for each and every element in the array.
array3 = array2.map(Math.sqrt)
array3; // [ 0, 2, 3, 4, 5, 99, 100 ]
- reduce(): Reduce values of an array to one value.
var array = [0,2,3,4,5,99,100];
var s = array.reduce(function sub(total, num) {
return total + num; // 213
});
- slice(): Select and return part of an array.
var array = [1, 2, 5, 99, 101];
array.slice(0, 2); // [ 1, 2 ]
- splice(): Add/remove element from an array.
var lang = ["HTML", "CSS", "JS", "Bootstrap"];
var removed = lang.splice(2, 1, 'PHP', 'React');
console.log(lang); // HTML,CSS,PHP,React,Bootstrap
console.log(removed); // JS
These methods will come in handy when working with data on the web and I hope you have a fair understanding of the most important ones by now.
Thank You!
Top comments (4)
I thought 'slice' method will create a copy of the existing array. Enlighten me here.
Yes! slice will create a copy of the existing array when assigned to a new value, the original array is not bothered. Example:
Output:
["school", "college", "restaurant", "hospital"]
["school", "college"]
Great. So the conclusion is that if you dont specify the arguments (0,2), arr.slice() will reproduce the original array right?
Yes! Just
arr.slice()
will reproduce the original array.