javascript most used array functions

forEach for looping through each array element.
[code language=”javascript”]
var fruits = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Orange’, ‘Pear’];
fruits.forEach(function (fruit) {
console.log(fruit);
});
// Apple
// Banana
// Cherry
// Orange
// Pear
[/code]

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.
[code language=”javascript”]
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’ ]
[/code]

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.
[code language=”javascript”]
var fruits = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Orange’, ‘Pear’];
var strLenGt4 = fruits.filter(function (fruit) {
return fruit.length > 4;
});
console.log(strLenGt4); // [ ‘Apple’, ‘Banana’, ‘Cherry’, ‘Orange’ ]
[/code]

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.
[code language=”javascript”]
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
[/code]

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.
[code language=”javascript”]
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 ]
[/code]

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.
[code language=”javascript”]
var fruits = [‘Apple’, ‘Banana’, ‘Cherry’, ‘Orange’, ‘Pear’];
console.log(fruits.join(",")); // Apple,Banana,Cherry,Orange,Pear
[/code]

concat concatenate two arrays into one array.
[code language=”javascript”]
console.log([1,2,3].concat([4,5,6])); // [ 1, 2, 3, 4, 5, 6 ]
[/code]

shift removes the first element from an array and returns that element. The original array will have one less element.
[code language=”javascript”]
var n = nums.shift();
console.log(n); // 1
console.log(nums); // [ 2, 3, 4, 5, 6, 7, 8, 9 ]
[/code]

Search within Codexpedia

Custom Search

Search the entire web

Custom Search