Skip to content

Instantly share code, notes, and snippets.

@AvgustPol
Last active October 9, 2019 14:15
Show Gist options
  • Save AvgustPol/2907b73b4eb8e9d48fbbb8b22a7992a1 to your computer and use it in GitHub Desktop.
Save AvgustPol/2907b73b4eb8e9d48fbbb8b22a7992a1 to your computer and use it in GitHub Desktop.
8 Must Know JavaScript Array Methods
//return true if every item returns true
let items = [
{ name: 'Bike', price: 400 },
{ name: 'TV', price: 1200 }
];
let cheapPrice = 1000;
let everyItemsHasCheapPrice = items.every((item) => {
return item.price <= cheapPrice
});
everyItemsHasCheapPrice // false
const filteredItems = items.filter((item) => {
return item.price <= 100
});
return very first item in array
const foundItem = items.find((item) => {
return item.name == "Antonio"
});
items.forEach((item) => {
//here do something with item
console.log(item.name)
});
const items = [ 1 , 2, 3, 4, 5 ]
boolean includesTwo = items.includes(2) // true
boolean includesTwo = items.includes(7) // false
const items = [
{ name: 'Bike', price: 100 },
{ name: 'TV', price: 200 },
{ name: 'Album', price: 10 },
{ name: 'Book', price: 5 },
{ name: 'Phone', price: 500 },
{ name: 'Computer', price: 1000 },
{ name: 'Keyboard', price: 25 },
]
convert one array to another
const itemNames = items.map((item) => {
return item.name
});
reduce method do some operations on the array and returns the new array as result:
e.g. get total price of all items:
let initialValue = 0;
const total = items.reduce((reducerVal, item) => {
return item.price + reducerVal
}, initialValue )
return true if at least one item returns true
number cheapPrice = 100;
boolean hasSomeCheapItems = items.some((item) => {
return item.price <= cheapPrice
})
@AvgustPol
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment