본문 바로가기

html | javascript

html javascript - array filter

 const arr0 = ['car','bus','aircraft','spacecraft','car1','motorcycle','car']
 const arr1 = [
   {name: 'car', type: 'land', cost: 100},
   {name: 'bus', type: 'land', cost: 50},
   {name: 'aircraft', type: 'sky', cost: 200},
   {name: 'motorcycle', type: 'land', cost: 80},
   {name: 'spacecraft', type: 'space', cost: 1000}
]
const arr2 = [5,3,21,6,50,100,1,10,12,20,2]

const filter0 = arr0.filter(str => str === 'car')
const filter1 = arr0.filter(str => str.includes('craft'))
console.log(filter0) // ['car', 'car']
console.log(filter1) // ['aircraft', 'spacecraft']

const filter2 = arr1.filter(obj => {
  return obj.type === 'land' && obj.cost > 50
})
console.log(filter2) // car, motorcycle

const filter3 = arr2.filter(num => num < 10)
console.log(filter3) // [5, 3, 6, 1, 2]