let myFriends = ['Ramesh', 22, 'male', 'Arjun', 20, 'male', 'Vishal', true, 52];
In JavaScript, we have an Array class, and arrays are the prototype of this class. Example ↓
let myFriends = new Array; // optional
myFriends = ['Ramesh', 22, 'male', 'Arjun', 20, 'male', 'Vishal', true, 52];
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
console.log(myFriends.length);
We use 'for' loop to navigate.
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
for(let i = 0; i < myFriends.length; i++) {
console.log(myFriends[i]);
}
Output ↓
Vinod
Ramesh
Arjun
Vishal
After ES6 we have for..in and for..of loop too
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
for(let ele in myFriends) {
console.log(myFriends[ele]);
}
for(let ele of myFriends) {
console.log(ele);
}
let myFriends = ['Vinod','Ramesh','Arjun','Vishal'];
myFriends.forEach(function(element, index, array) {
console.log(element + " index : " + index + " " + array);
});
let myFriendNames = ["vinod","bahadur","thapa","thapatechnical","thapa"];
console.log(myFriendNames.indexOf("Thapa", 3));
// second argument is the index number from which it will start searching.
let myFriendNames = ["vinod","bahadur","thapa","thapatechnical","thapa"];
console.log(myFriendNames.lastIndexOf("Thapa", 3));
let myFriendNames = ["vinod","bahadur","thapa","thapatechnical","thapa"];
console.log(myFriendNames.includes("Thapa"));
const prices = [200, 300, 350, 450, 500, 600];
const findElem = prices.find((currVal) => currVal < 400);
console.log(findElem); // 200
console.log(prices.find((currVal) => currVal > 1400)); // undefined
const prices = [200, 300, 350, 450, 500, 600];
console.log(prices.findIndex((currVal) => currVal > 1400)); // -1
const prices = [200, 300, 350, 450, 500, 600];
const newPriceTag = prices.filter((elem, index) => {
return elem > 300;
});
console.log(newPriceTag); // [ 350, 450, 500, 600 ]
const months = ['March', 'Jan', 'Feb', 'April' , 'Dec', 'Nov'];
console.log(months.sort());
const array1 = [1, 30, 4, 21, 100000, 99];
console.log(array1.sort()); // sorted according to the first digit.
// In JS numbers 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.
1- How to sort the numbers in the array in ascending (up) and descending (down) order?
// Ascending
// we have to create an additional function
compareFunction = (a, b) => {
// 1. < 0 ... a comes first
// 2. 0 ... nothing will be changed
// 3. > 0 ... b comes first
return a - b;
}
const numbers = [1, 30, 4, 21, 100000, 99];
console.log(numbers.sort(compareFunction));
// Descending
compareFunction = (a, b) => {
return b - a; // changes
}
const numbers = [1, 30, 4, 21, 100000, 99];
console.log(numbers.sort(compareFunction));
2- Sort the array ["Banana", "Orange", "Apple", "Mango"] in descending order
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();
// Now we are going to use Array.prototype.reverse()
// The reverse() method reverses an array in place.
// The first array element becomes the last, and the last array element becomes the first.
console.log(fruits);
fruits.reverse();
const animals = ['pigs', 'goats', 'sheep'];
const count = animal.push('chicken');
console.log(count); // 4
animals.push('cats', 'cow', 'tiger');
const animals = ['pigs', 'goats', 'sheep'];
const count = animals.unshift('chicken');
console.log(count);
console.log(animals);
animals.unshift('chicken', 'cats','cow');
console.log(animals);
// one more example
const myNumbers = [1,2,3,5];
myNumbers.unshift(4,6);
console.log(myNumbers);
const plants = ['broccoli', 'cauliflower', 'kale', 'tomato', 'cabbage'];
console.log(plants);
console.log(plants.pop());
console.log(plants);
const plants = ['broccoli', 'cauliflower', 'kale', 'tomato', 'cabbage'];
console.log(plants);
console.log(plants.shift());
console.log(plants);
Using only one method perform CRUD operation on an array.
We are going to use Array.prototype.splice() which adds and removes elements from an array.
const months = ['Jan', 'march', 'April', 'June', 'July'];
// sol 1
const newMonths = months.splice(months.length, 0, "Dec");
// sol 2
console.log(newMonths); // empty array as not elements are deleted
// sol 3
if(months.indexOf("march") == -1) {
console.log("Data not found");
} else {
months.splice(months.indexOf("march"), 1, "March");
}
// sol 4
if(months.indexOf("June") == -1){
console.log("Data not found");
} else {
months.splice(months.indexOf("June"), 1);
}
const array = [1, 4, 8, 16, 25];
// if we want an array which have elements greater than 9
let newArr = array.map((curEle, index, arr) => {
return curEle > 9;
});
console.log(newArr); // [false, false, false, true, true]
let newArr2 = array.map((curEle, index, arr) => {
return `Index no = ${index} and the value is ${curEle} belong to ${arr}`;
})
// sol 1
let arr = [ 25, 36, 49, 64, 81 ];
let arrSqr = arr.map((curEle) => Math.sqrt(curEle));
console.log(arrSqr); // [ 5, 6, 7, 8, 9 ]
// sol 2
// here we are going to use chaining method
let arr = [ 2, 3, 4, 6, 8 ];
let arr2 = arr.map((curEle) => {
return curEle * 2;
}).filter((curEle) => {
return curEle > 10;
});
console.log(arr2); // [ 16, 36, 64 ]
const subMarks = [ 44, 55, 44, 66, 55 ];
const totalMarks = subMarks.reduce((accumulator, curEle, curIn, arr) => {
return accumulator += curEle;
}, 25);
console.log(totalMarks);
How to flatten an array
Converting 2d and 3d array into one dimensinal array.
const arr = [
['zone_1', 'zone_2'],
['zone_3', 'zone_4'],
['zone_5', 'zone_6'],
['zone_7', 'zone_8'],
]
let flatArr = arr.reduce((accum, currVal) => {
return accum.concat(currVal)
})
console.log(flatArr);