javascript most used array functions

forEach for looping through each array element.

var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear'];
fruits.forEach(function (fruit) {
	console.log(fruit);
});
// Apple
// Banana
// Cherry
// Orange
// Pear

map creates a new array with the values returned from each callback function. This example loop through each fruit and change each fruit to juice, so the new array will contains juice instead of fruits.

var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear'];
var juice = fruits.map(function (fruit) {
	return fruit + ' juice';
});
console.log(juice); // [ 'Apple juice', 'Banana juice', 'Cherry juice', 'Orange juice', 'Pear juice' ]

filter creates a new array with all elements that pass the test implemented by the provided function. This example returns a new array with fruit name has string length greater than 4.

var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear'];
var strLenGt4 = fruits.filter(function (fruit) {
	return fruit.length > 4;
});
console.log(strLenGt4); // [ 'Apple', 'Banana', 'Cherry', 'Orange' ]

reduce applies a function against an accumulator and each value of the array (from left-to-right) has to reduce it to a single value. This example returns the sum of all the elements in the array. The total in the function argument is the previous returned value, curVal is the current value of the current element in the array.

var nums = [1,2,3,4,5,6,7,8,9];
var total = nums.reduce(function (total, curVal) {
	return total + curVal;
});
console.log(total); // 45

slice returns a shallow copy of a portion of an array into a new array object. The first example returns array elements starting from array index 3. The second example returns array elements from array index 3 to 5.

var nums = [1,2,3,4,5,6,7,8,9];
console.log(nums.slice(3));     // [ 4, 5, 6, 7, 8, 9 ]
console.log(nums.slice(3, 6)); 	// [ 4, 5, 6 ]

join concatenate each element in the array into a single string. This example changes the array of fruits into a string of fruits separated by commas.

var fruits = ['Apple', 'Banana', 'Cherry', 'Orange', 'Pear'];
console.log(fruits.join(",")); // Apple,Banana,Cherry,Orange,Pear

concat concatenate two arrays into one array.

console.log([1,2,3].concat([4,5,6])); // [ 1, 2, 3, 4, 5, 6 ]

shift removes the first element from an array and returns that element. The original array will have one less element.

var n = nums.shift();
console.log(n);		// 1
console.log(nums);	// [ 2, 3, 4, 5, 6, 7, 8, 9 ]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search