What is an Array?
an array is a data structure that contains group of elements typically these all are similar kinds of datatype such as integer,string etc we can individually fetch array elements and do all types of operation related to data manipulation etc
Creating an Array in javascript is done by 2 types shown below
const array_name = [item1, item2];
const arr = new Array(10)
Each individual elements inside array can be done indexing which starts from 0 all the way to nth index if we want to print first element in array we need to call array_name[0], array_name[1] etc
Some Important Methods of Array in JavaScript
split
split method converts a particular string into array elements so split method is defined
first example
let text = "How are you doing today?";
const myArray = text.split(" ");
console.log(myArray)
Output:-[ 'How', 'are', 'you', 'doing', 'today?' ]
second example
let text = "How 5 are 5 you 5 doing 5 today?";
const myArray = text.split("doing");
Output:-[ 'How 5 are 5 you 5 ', ' 5 today?' ]
in the above method split method search for the string delimiter on which split of the string will occur and accordingly splits the whole string into respective words and then as array elements
slice
syntax
slice()
slice(start)
slice(start, end)
the slice method returns the portion of array selected and returns it as a new array it does not modify the object array
A negative index can be used, indicating an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
If start is undefined, slice starts from the index 0.
If start is greater than the index range of the sequence, an empty array is returned. example 1
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(-2));
Output:- Array ["duck", "elephant"]
example 2
console.log(animals.slice(2));
Output:-Array ["camel", "duck", "elephant"]
example 3
console.log(animals.slice(2, 4));
Output:-Array ["camel", "duck"]
example 4
console.log(animals.slice(0,-2));
Output:-Array ["ant", "bison","camel"]
splice
splice(startIndex)
splice(startIndex, deleteCount)
splice(startIndex, deleteCount, item1)
splice(startIndex, deleteCount, item1, item2, itemN)
the splice method changes the array contents i.e modifying the array and remove some elements in array optionally also adding some elements in array
const months = ['Jan', 'March', 'April', 'June'];
console.log(months.splice(1, 0, 'Feb'))
Output:- Array ["Jan", "Feb", "March", "April", "June"]
above example search the 1st index but doesnt delete the element since next parameter is zero instead inserts the value Feb
const myFish = ['angel', 'clown', 'drum', 'mandarin', 'sturgeon'];
const removed = myFish.splice(3, 1);
Output: myFish is ["angel", "clown", "drum", "sturgeon"]
removed is ["mandarin"]
example: remove elements from end index with -n index
const myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];
const removed = myFish.splice(-2, 1);
Output:- myFish is ["angel", "clown", "sturgeon"]
removed is ["mandarin"]
example: remove elements from middle 2nd index
const myFish = ['angel', 'clown', 'drum', 'sturgeon'];
const removed = myFish.splice(2, 1, 'trumpet');
Output:-["angel", "clown", "trumpet", "sturgeon"]
fill
in array fill method it changes all the values from start index to end index
fill(value)
fill(value, start)
fill(value, start, end)
const array1 = [1, 2, 3, 4];
console.log(array1.fill(0, 2, 4));
Output:- [1, 2, 0, 0]
above methods fills the array from postion 2 to position 4
console.log(array1.fill(6));
Output: [6, 6, 6, 6]
### concat
The concat() method concatenates (joins) two or more arrays:
const arr1 = ["Cecilie", "Lone"];
const arr2 = ["Emil", "Tobias", "Linus"];
const children = arr1.concat(arr2);
Output:["Cecilie", "Lone","Emil", "Tobias", "Linus"]
includes
The includes method says whether an array includes certain value among its entities returning true or false
const pets = ['cat', 'dog', 'bat'];
console.log(pets.includes('cat'));
Output: true
push
it adds one or more elements to end of array and returns new length of array
const animals = ['pigs', 'goats', 'sheep'];
animals.push('chickens', 'cats', 'dogs');
console.log(animals);
Output:- Array ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]
usually we use array push in use cases while we iterate over an array
cars = ["BMW 760", "Audi S8", "Bugatti","Lemborgini"]
for (var a=1; a<=5; a++)
cars.push(a)
console.log(cars)
Output:-["BMW 760", "Audi S8", "Bugatti","Lemborgini",1,2,3,4,5]
another example by pushing it on new array
let contry = ["India", "Sweden", "Norway", "Iceland"];
let newContry=[];
for (let newContry1 of contry){
newContry.push(newContry1.toUpperCase())
}
console.log(newContry);
pop
Remove the last item from array
shift()
Remove the first element from array and returns the new element it changes the length of array i.e modifies the array
const myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
const shifted = myFish.shift();
console.log("removed this element",shifted)
console.log(myFish)
Output:- removed this element angel
['clown', 'mandarin', 'surgeon']
unshift()
Unshift add one or more elements to beginning of the array and changes the array length note that unshift only returns the new array length but to see the new array you need to console the array
const array1 = [1, 2, 3];
console.log(array1.unshift(4, 5));
output: 5
console.log(array1);
output: Array [4, 5, 1, 2, 3]
findIndex
findIndex returns the index of the first element of array upon results generated by the callback function if no matching elements are found is present then -1 result is returned
Syntax findIndex((element) => { / … / } )
const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13; //callback function
console.log(array1.findIndex(isLargeNumber));
output: 3
indexOf
indexOf returns the first index of the element which is found if none found then -1 is returned ma const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];
console.log(beasts.indexOf('bison'));
output: 1
map()
The map function returns a new array by calling every element in the array modifies the array elements based on the results of the calling function and returns a new array
const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
output: Array [2, 8, 18, 32]
example 2
let arr = [3, 4, 5, 6];
let modifiedArr = arr.map(function(element){
return element *3;
});
console.log(modifiedArr);
Output:[9, 12, 15, 18]
filter()
filter in array is used to filter out a portion of the array based on the callback function result it returns those results if none of the conditions matches the callback function the original array is returned
function isBigEnough(value) {
return value >= 10;
}
const filtered = [12, 5, 8, 130, 44].filter(isBigEnough);
Output:-[12, 130, 44]
reduce()
the reduce method works on every elements present in array a reduces function runs in the background popularly used while finding the sum of all the elements in an array
const nos=[1,-1,2,3];
let sum = 0;
const sum= nos.reduce(accumulator,currentValue) =>{
return accumulator+currentValue
},0);
reduce method takes 2 mandatory arguments one optional argument it goes like this accumulator,currentValue,initialValueofAccumulator(optional)
accumulator is set to zero initial value current value is picked up one by one and the accumulator value gets updated accordingly and finally its returns the sum
lets understand in depth a=initialValueofAccumulator = accumulator c=1=initialValue of array = currentValue of array
initialValueofAccumulator is the optional value passed after , in reduce method
according to the picture a=0 c=1 so accumulator a value will be 1 next a=1 but c =-1 so accumulator a value will be zero next a=0 but c=2 so accumulator a will be 2 next a=2 but c=3 so accumulator a will be 5
finally it will only print out the accumulator value which tends to be the sum of array i.e 5
Note that in case we dont provide the optional value the 1st value in the array is automatically initialized in the accumulator in that case a=1