Array Method
What is different between forEach and map method
Ans. map method returns a new array by applying the callback function on
each element of an array, while the forEach method doesn't return anything.
//Array Methods
const shop = [
{ id: 1, name: "apple", cat: "frutes", price: 20 },
{ id: 2, name: "mango", cat: "frutes", price: 30 },
{ id: 3, name: "banana", cat: "frutes", price: 40 },
{ id: 4, name: "tomatos", cat: "vegs", price: 50 }
]
//ForEach
const fordata = shop.forEach((item) => {
console.log(`price for ${item.name} is ${item.price}`);
//return item.price
})
console.log(fordata);
//Map
const newpricemap = shop.map((item) => {
return { name: item.name, price: item.price * 2 }
})
console.log(newpricemap);
//Filter
const filtercat = shop.filter((item) => {
return item.cat === 'vegs';
})
console.log(filtercat)
//Find
const findcat = shop.find((item) => {
return item.cat === "frutes"
})
console.log(findcat)//FindIndex
const findIndexcat = shop.findIndex((item) => {
return item.cat === "vegs"
})
console.log(findIndexcat)
const shop = [
{ id: 1, name: "apple", cat: "frutes", price: 20 },
{ id: 2, name: "mango", cat: "frutes", price: 70 },
{ id: 3, name: "banana", cat: "frutes", price: 40 },
{ id: 4, name: "tomatos", cat: "vegs", price: 100 }
]
// sort array
const sortedArray = shop.sort((a, b) => {
return a.name.localeCompare(b.name);
})
console.log(sortedArray);
//some array and every array like (|| AND && condition and return true or false)
const someData = shop.some((item) => {
return item.cat === 'frutes'
})
console.log(someData);
const everyData = shop.every((item) => {
return item.price > 15
})
console.log(everyData);
//reduce array
let intialval = 0;
const totalPrice = shop.reduce((currentTotal, item) => {
return item.price + currentTotal;
}, intialval)
console.log(totalPrice);
//Includes array
const number = [1, 2, 3, 4, 5];
console.log(number.includes(6))
// Concat Array
const number1 = [1, 2, 3, 4, 5];
const words = ["a", "b", "c"];
console.log(number1.concat(words));
//flat aaray (by default 1 value )
const number2 = [1, 2, 3, 4, 5, [6, 7, [8, 9]]];
console.log(number2.flat(2));
//flatmap array
const flatmapdata = number2.flat(2).map((item) => {
return item * 10;
});
console.log(flatmapdata);
0 Comments
Post a Comment