Array in Java Script
- Arrays are list-like objects which user can store data and manipulate,
- Array objects in Java Script has built in methods to perform operations,
- An array is a special variable, which can hold many values
- Arrays highly used data structure in any language as well as JavaScript
Creating array normal way in java script (es6)
const array_name = [item1, item2, ...];
Creating Array using new keyword
const array_name = new Array(item1, item2,item3,.......);
Accessing array item using index
let cars = ['BMW', 'Volvo']
console.log(cars.length)
Add an item to the end of an Array
let cars = ['BMW', 'Volvo']
cars.push('Tesla')
Remove an item from an Array
let cars = ['BMW', 'Volvo']
cars.push('Tesla')
let last = cars.pop()
Find index of element in array
let pos = cars.indexOf('Volvo')
Array.prototype.concat()
- The concat() method is used to merge arrays. This method does not change the existing arrays, but instead returns a new array.
const array1= [1,2,3];
const array2 = [4,5,6];
const array3 = array1.concat(array2);
console.log(array3);
// expected output: Array [1,2,3,4,5,6]
Array.prototype.filter()
- The filter() method creates a new array which satisfies the given condition
const words = ['neogcamp', 'HTML', 'Tanay Pratap', 'ReactJs', 'CSS'];
const result = words.filter(word => word.length > 5);
console.log(result);
Array.prototype.map()
- The map() method creates a new array populated with the results of calling a provided function on every element in the calling array.
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 5);
console.log(map1);