const collection = [1, 2, 3, 4, 5, 6, 7, 8];
const flowers = [
{
name: "Rose",
price: 30,
},
{
name: "Orchid",
price: 150,
},
{
name: "Lily",
price: 100,
},
{
name: "Tulip",
price: 80,
},
];
// includes - includes checks if the array includes the item passed.
console.log(collection.includes(4)); //true
console.log(collection.includes(9)); //false
// some - checks if there is atleast one of the item in array that passes the given condition.
const largeNum = collection.some((num) => num > 4);
console.log("Large Number", largeNum); //true
const negativeNum = collection.some((num) => num < 0);
console.log("Negative Number", negativeNum); // false
// every - checks if all the items in the array pass the given condition.
const lessThanNine = collection.every((num) => num < 9);
console.log("Less than 9", lessThanNine); // true
const lessThanFive = collection.every((num) => num < 5);
console.log("Less than 5", lessThanFive); // false - not all are less than 5
//filter - returns a new array that pass the particular given condition
const filtered = collection.filter((num) => num > 3);
console.log("Filtered", filtered); // [4,5,6,7,8]
//map - return new array with results of the called function.
const addThree = collection.map((num) => num + 3);
console.log("Array with 3 added", addThree); // [ 4, 5, 6, 7, 8, 9, 10, 11 ]
//reduce - Applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.
const flowerPricesTotal = flowers.reduce((sum, flower) => {
// console.log(sum, flower);
return sum + flower.price;
}, 0); //optionally supplied initial value. If not given, the 0th element of the array is considered.
console.log("Flower Prices", flowerPricesTotal); //360
// Question - Write a script to find the sum of ages of all dogs in years.
// const animals = [
// {
// age: 24,
// type: "dog",
// },
// {
// age: 60,
// type: "dog",
// },
// {
// age: 36,
// type: "cat",
// },
// ];
// Age is in months, has to be converted in months.
// const dogs = animals.filter((animal) => animal.type === "dog");
// console.log("Dogs", dogs);
// const dogsAgeTotal = dogs.reduce((age, dog) => {
// return age + dog.age;
// }, 0);
// console.log("Dogs Total Age", dogsAgeTotal / 12);
// const dogsTotalAge = animals
// .filter((animal) => animal.type === "dog")
// .map((animal) => animal.age / 12)
// .reduce((age, dog) => {
// return age + dog;
// }, 0);
// console.log("Dogs Total Age", dogsTotalAge);
let result = animals.reduce((totalAge, item) => {
return item.type === "dog" ? totalAge + item.age : totalAge;
}, 0);
console.log(result / 12);
Created
April 6, 2021 05:17
-
-
Save anushka-beri/32999039c5e015a52184de56c9fc4490 to your computer and use it in GitHub Desktop.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment