Array in JavaScript
Lets see what are Array in Javascript, Array in general is spacial type of Data structure used to store collections of elements. Unlike other programming language in JS array can store elements of different data types for example const arr = [1, "one", true, {name:"array"},2,"two", ["JS","Python"]]
Array in JS is treated as Objects and let see what are the array properties and methods we have in JS ? Lets consider below Array
const numbers = [1,2,3,4,5,6,3,4,5];
To check the lenght of the array
console.log(numbers.length) // 9
Check index of the element
Will return the index of the first element matches, if not found -1 will be returned
console.log(numbers.indexOf(2)) // 1
Add new element at end
numbers.push(10) // [1,2,3,4,5,6,3,4,5,10]
Add new elemet at begining
numbers.unshift(8) // [8,1,2,3,4,5,6,3,4,5,10]
To remove last element
numbers.pop() // [8,1,2,3,4,5,6,3,4,5]
To remove first element
numbers.shift() // [1,2,3,4,5,6,3,4,5]
Array slice:
method will remove the selected elements from array
numbers.slice(1,3) // [2,3]
Array splice :
method is used to add new element to the array or remove element inplace At position 1, add 10
numbers.splice(1,0,20) // [1, 20, 2, 3, 4, 5, 6, 3, 4, 5]
At position 2, remove 2 items
numbers.splice(2,2) // [1, 20, 4, 5, 6, 3, 4, 5]
forEach method
forEach method is used to iterate all the elements of the array. This method will accept callback function as argument and this callback function can accept upto three parameters. First - current element of an Array Second - index of the current element Third (optional) - complete array itself
numbers.forEach((item,index) => console.log(item,index))
//
1 0
20 1
4 2
5 3
6 4
3 5
4 6
5 7
Now lets discuss few of the commonly used methods. All these methods accepts arguments similar to forEach method and and will return new array. Lets consider new array.
const arr = [1,2,3,4,5]
Map:
is used to update elements of array
let result = arr.map((item) => item*2)
console.log(result) // [ 2, 4, 6, 8, 10 ]
Filter:
is used to filter items from array, it returns new array based on true or false.
result = arr.filter((item) => item > 3)
console.log(result) // [ 4, 5 ]
Find:
will return the value from the array which satisfy the condition else undefined
result = arr.find((item) => item === 3)
console.log(result) // 3
Reduce:
reduce the array to a single value and executes a provided function for each value of the array and the return value of the function is stored in an accumulator. This method accepts second argument which will be considered at first iteration.
result = arr.reduce((previous,current) => previous + current, 0)
console.log(result) // 15