----: Arrays In JavaScript :----
When we use var we can stored only one value at a time.
When we feel like storing multiple values in one variables then
instead of var, we will use an Array.
In JavaScript, we have an Array class, and arrays are the prototype
of this class.
eg.
var myFriends =["Ankit" , "Ankur" , "Dheeraj" , "Santosh"];
1. Traversal of an Array
2. Searching and filter in an Array
3. How to sort and compare an Array
4. How to insert,Add,Replace and delete elements in Array (CRUD)
5. Map(), Reduce(), Filter()
🌟 Traversal In Array (Navigate through Array) :-
if we want to get the single data at a time and also
if we want to change the data
var myFriends = ["Rames" , "Suresh" , "Mahesh"]
console.log(myFriends[2]);
if we want to check the length of elements of an array.
console.log(myFriends.length);
we use for loop to navigate
var myFriends = ["Ram" , "Shyam" , "Mohan" , "Gita"]
for(var i=0; i<myFriends.length; i++){
console.log(myFriends[i]);
}
After ES6 we have for..in and for..of loop too
for in (It prints the numbers of the values)
var myFriends = ["Ram" , "Shyam" , "Mohan" , "Gita"]
for(let elements in myFriends){
console.log(elements);
}
for off (it prints the value)
var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
for(let elements of myFriends){
console.log(elements);
}
Array.prototype.forEach()
Calls a function for each element in the array.
var myFriends = ['Ram','shyam','gita','sita']
myFriends.forEach(function (element,index,array){
console.log(element + " index : " + index + " " + array);
})
Fat arrow function
myFriends.forEach((element,index,array) => {
console.log(element + " index : " + index + " " + array);
})
🌟 Searching and filter in an Array
Array.prototype.indexOf()
Return the first (least) index of an element within the array equal
to an element, or -1 if none is found. It search the element from the
0th index number
var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
console.log(myFriends.indexOf("Mohan", 2));
Array.prototype.lastIndexOf()
Return the last(greatest) index of an element within the array equal
to an element, or -1 if none is found. It search the element last to
First.
var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
console.log(myFriends.lastIndexOf("Mohan", 2));
Array.prototype.includes()
Determines whether the arrays contains a value,
returning true or false as appropriate.
var myFriends = ["Ram" , "shyam" , "Mohan" , "Gita"]
console.log(myFriends.includes("shyam"));
Array.prototype.find()
arr.find(callback(element[, index[, array]])[, thisArg])
Returns the found element in the array, if some element in the
array satisfies the testing function, or indefined if not found.
only problem is that it return only one element.
const prices = [200,250,300,350,400,500]
const findElem = prices.find((currVal)=>{
return currVal < 400
})
console.log(findElem);
Array.prototype.findIndex()
Return the found index in the array, if an element in the
array satisfies the testing function or -1 if not found.
const prices = [200,250,300,350,400,500]
console.log(prices.findIndex((currVal)=> currVal < 400));
Array.prototype.filter()
Return a new array containing all elements of the calling
array for which the provided filtering function returns true.
const prices = [200,250,300,350,400,500]
const newPriceTag = prices.filter((elem,index) => {
return elem < 400;
})
console.log(newPriceTag);
🌟 How to short an Array
Array.prototype.sort()
The sort() method sorts the elements of an array in place and
return the sorted array. The default sort order is ascending, built
upon converting the elements into strings,
then comparing there sequence of UTF-16 code units values.
const months = ["Feb" , "Dec" , "May" , "Oct"];
console.log(months.sort());
const array1 = [1,23,7,89,786,5675,5,65,];
console.log(array1.sort());
However, if number are sorted as strings,
"25" is bigger than 100, because "2" is bigger than "1".
Because of this, the sort() method will produce an incorrect
result when sorting numbers.
🌟 Perform CRUD [Insert/add]
Array.protoype.push()
The push() method adds one or more element to the
end of an array and return the new length of the array.
const animals = ["Pigs" , "goat" , "Sheep"];
animals.push("chicken","Cow");
console.log(animals);
Array.prototype.unshift()
The unshift() method adds one or more elements to the
begining of an array and return the new length of the array.
const animals = ["Pigs" , "goat" , "Sheep"];
animals.unshift("chicken","Cow");
console.log(animals);
Array.prototype.pop() [delete/remove last one]
The pop() method removes the last element from an array and return
that element. This method changes the length of the array.
const vegetables = ["Tomato" , "Potato" , "Bringal" , "cauliflower" ];
console.log(vegetables);
console.log(vegetables.pop());
console.log(vegetables);
Array.prototype.shift()
The shift() method removes the first element from an array and
returns that removes element. This method changes the length of the
array.
const vegetables = ["Tomato" , "Potato" , "Bringal" , "cauliflower" ];
console.log(vegetables);
console.log(vegetables.shift());
console.log(vegetables);
Challenge Time :-
Array.prototype.splice()
Adds and/or removes element from an array.
Q1. Add Dec at the end of an array.
Q2. What is the return value of splice method?
Q3. update march to March (update).
Q4. Delete june from an array.
const months = ['jan','march','April','June','July']
sol1:
const newMonth = months.splice(5,0,"Dec");
console.log(months);
sol2:
console.log(newMonth);
sol3:
a.
const months = ['jan','march','April','June','July']
const updateMonth = months.splice(1,1,'March');
console.log(months);
b.
const months = ['jan','march','April','June','July']
const indexOfMonth = months.indexOf("march");
if(indexOfMonth != -1){
const updateMonth = months.splice(indexOfMonth,1,"March");
console.log(months);
}else{
console.log("No such data found");
}
sol4:
const months = ['jan','march','April','June','July']
const indexOfMonth = months.indexOf("June");
if(indexOfMonth != -1){
const updateMonth = months.splice(indexOfMonth,1);
console.log(months);
}else{
console.log("No such data found");
}
🌟 Array subsection (Map and Reduce Method)
Array.prototype.map()
let newArray = arr.map(callback(currentValue[,index[, array]]){
return element for newArray, after executing something
}[,thisArg]);
Return a new array containing the result of calling a
function on every element in this array.
const array1=[1,4,9,16,25];
// num > 9
let newArr = array1.map((curElement,index,arr)=>{
return curElement > 9;
})
console.log(array1);
console.log(newArr);
const array1=[1,4,9,16,25];
let newArr = array1.map((currElem,index,arr)=>{
return ` Index no = ${index} and the value is ${currElem} belongs to ${arr}`
})
console.log(newArr);
it return new array without mutating the original array.
Challenge time
Q1. Find the square root of each element in an array?
Q2. Multiply each element by 2 and return only those
element which are greater than 10?
sol1.
let arr = [25,36,49,64,81];
let arrSquare = arr.map((currElem)=>{
return Math.sqrt(currElem);
})
console.log(arrSquare);
sol2.
let arr = [2,3,4,6,8];
let arr2 = arr.map((currElem)=>{
return currElem * 2;
}).filter((currentValue)=>{
return currentValue>10;
})
console.log(arr2);
we can ue channing too
REDUCE METHOD :-
Flatten an array means to convert the 3d array into a single
dimensional array
The reduce() method executes a reducer function( that you provide)
on each element of the array,resulting in the single output values.
The reducer function takes four arguments:
Accumulator
Current Value
Current Index
Source Array
let arr = [5,9,4,7];
let sum = arr.reduce((accumulator , curElem,index,arr)=>{
return accumulator += curElem;
},7)
console.log(sum);
How to fatten an array
converting 2d and 3d array into one dimensional array
const arr = [
['zone_1' , 'zone_2'],
['zone_3' , 'zone_4'],
['zone_5' , 'zone_6'],
['zone_7' , 'zone_8']
];
let flatArr = arr.reduce((accumulator,currVal)=>{
return accumulator.concat(currVal);
})
console.log(flatArr);
flat() Mehthod :-
const arr = [
['zone_1' , 'zone_2'],
['zone_3' , 'zone_4'],
['zone_5' , 'zone_6'],
['zone_7' , 'zone_8']
];
console.log(arr.flat(Infinity));