Skip to content

Latest commit

 

History

History
173 lines (121 loc) · 2.63 KB

js-array-8-must-know.md

File metadata and controls

173 lines (121 loc) · 2.63 KB

8 Must Know JavaScript Array Methods

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 }
]

1. filter

const filteredItems = items.filter((item) => {
    return item.price <= 100
})

console.log(filteredItems)
[
  { name: 'Bike', price: 100 },
  { name: 'Album', price: 10 },
  { name: 'Book', price: 5 },
  { name: 'Keyboard', price: 25 }
]

2. map

[
  'Bike',     'TV',
  'Album',    'Book',
  'Phone',    'Computer',
  'Keyboard'
]

3. find

find a single object in an array

const foundItem = items.find((item) => {
    return item.name === 'Book'
})
{ name: 'Book', price: 5 }

4. forEach

items.forEach((item) => {
    console.log(item.price)
})
100
200
10
5
500
1000
25

5. some

return true if any items in array satisfy some condition.

const hasInexpensiveItems = items.some((item) => {
    return item.price <= 100
})
true

6. every

return true if all items in array satisfy some condition

const allInexpensiveItems = items.every((item) => {
    return item.price <= 100
})
false

7. reduce

const total = items.reduce((currentTotal, item) => {
    return item.price + currentTotal
}, 0)
1840

8. include

const numbers = [1,2,3,4,5]
const includesTwo = numbers.includes(2)
console.log(includesTwo)
true