Javascript Array Methods
Some popular methods [functions which are property of an object] of array are: push, pop, shift, unshift, forEach, map, filter and reduce.
Push and unshift method is used to insert elements at the end and beginning of an array and return the new length of array.
let fruits = ["apple", "banana", "tomato"]
console.log(fruits.push("pear")) // 4
console.log(fruits.unshift("guava")) // 5
console.log(fruits) // ['guava', 'apple', 'banana', 'tomato', 'pear']Pop and shift methods remove the last and first elements respectively of an array and returns it. These return undefined for empty array.
let fruits = ['guava', 'apple', 'banana', 'tomato', 'pear']
fruits.pop() // pear
fruits.shift() // guavaJust Remember: Two main way to access properties in js, value.x or value[x]: The dot is literal name of property to get value whereas value[x] the expression between brackets is evaluated to get the property name. value.x fetches the property of value named ‘x’ value.x or value[i].
Get Sagar Kumar’s stories in your inbox
Join Medium for free to get updates from this writer.
There are various methods to iterate in javascript arrays. Some widely used are: map, filter, reduce and forEach.
Map is used, for getting a new array from previous array with a function applied on each element.
Filter is used, for getting a new array with filtered elements based on test function provided.
Reduce method is used to return a calculated output based on callback function and initial value. It can be used to return any datatype.
forEach is used to apply some function to every elements in array and doesn’t return anything.
let fruits = ["apple", "banana", "cucumber"]
let paddedFruits = fruits.map(fruit => fruit.padEnd(10, "*"))
let moreThanFiveChar = fruits.filter(fruit => fruit.length > 5)
let concatenatedFruits = fruits.reduce((acc, curr)=> acc + " " + curr.padEnd(10, '*'),"")
console.log(paddedFruits, moreThanFiveChar, concatenatedFruits)
['apple*****', 'banana****', 'cucumber**']
['banana', 'cucumber']
' apple***** banana**** cucumber**'







