프론트엔드/Javascript 연습과제 해답

자바스크립트 문법 7 - 배열(Array)의 다양한 메서드 1 (검색과 조회) 해답

syleemomo 2022. 1. 14. 14:30
728x90

 

* 연습과제 1

const lyrics = `
Sorry Sorry Sorry Sorry
내가 내가 내가 먼저
네게 네게 네게 빠져
빠져 빠져 버려 baby
Shawty Shawty Shawty Shawty
눈이 부셔 부셔 부셔
숨이 막혀 막혀 막혀
내가 미쳐 미쳐 baby
바라보는 눈빛 속에
눈빛 속에 나는 마치
나는 마치 뭐에 홀린 놈
이젠 벗어나지도 못해
걸어오는 너의 모습
너의 모습 너는 마치
내 심장을 밟고 왔나봐
이젠 벗어나지도 못해
어딜 가나 당당하게
웃는 너는 매력적
착한 여자 일색이란
생각들은 보편적
도도하게 거침 없게
정말 너는 환상적
돌이킬 수 없을만큼
네게 빠져 버렸어
Sorry Sorry Sorry Sorry
내가 내가 내가 먼저
네게 네게 네게 빠져
빠져 빠져 버려 baby
Shawty Shawty Shawty Shawty
눈이 부셔 부셔 부셔
숨이 막혀 막혀 막혀
내가 미쳐 미쳐 baby
딴딴 딴따다 따 따란딴
딴딴 딴따다 따
네게 반해버렸어 baby
딴딴 딴따다 따 따란딴
딴딴 딴따다 따 따라빠빠라
Hey girl gir gir gir gir girl i
눈만뜨면 니 생각 Hey girl
자나깨나 사실 너 하나 밖에 안보여
말해봐 니 맘에 내가
말해봐 자리 잡았는지
말해줘 내게 말해줘
나는 바보 바보 바보
주변 사람들은 말해
내가 너무 적극적
이 세상에 그런 사람
어디 한둘이냐고
그걸 몰라 그녈 몰라
시기하며 하는 말
내가 부럽다면 그건
그대들이 지는 거
Sorry Sorry Sorry Sorry
내가 내가 내가 먼저
네게 네게 네게 빠져
빠져 빠져 버려 baby
Shawty Shawty Shawty Shawty
눈이 부셔 부셔 부셔
숨이 막혀 막혀 막혀
내가 미쳐 미쳐 baby
딴딴 딴따다 따 따란딴
딴딴 딴따다 따
네게 반해버렸어 baby
딴딴 딴따다 따 따라라라
딴딴 딴따다 따 따라빠빠라
Lets dance dance dance dance
Lets dance dance dance dance
Lets dance dance dance dance dance dance
Hey 이제 그만 내게 와줄래
정말 미칠 것만 같아 yeah
난 너만 사랑하고 싶어
절대 다시 한눈 팔 생각 없어 hey hey hey.
애인이라기보다 친구같은
내가 되고 싶어
너의 모든 고민 슬픔
함께 간직하고파
다시 없을 만큼 만큼
너를 너무 사랑해
내가 바란 사람 니가 바로 그
That that that girl
Sorry Sorry Sorry Sorry
내가 내가 내가 먼저
네게 네게 네게 빠져
빠져 빠져 버려 baby
Shawty Shawty Shawty Shawty
눈이 부셔 부셔 부셔
숨이 막혀 막혀 막혀
내가 미쳐 미쳐 baby
`
const keyword1 = 'Sorry'
const keyword2 = '부셔'

function searchWord(keyword, n){
    const searchedIndexes = []
    let foundIndex = lyrics.indexOf(keyword)

    while(foundIndex != -1){
        searchedIndexes.push(foundIndex)
        foundIndex = lyrics.indexOf(keyword, foundIndex+n)
    }
    return searchedIndexes.length
}

console.log(searchWord(keyword1, keyword1.length))
console.log(searchWord(keyword2, keyword2.length))

 

* 연습과제 2

const movies = [
    {title: 'Harry Potter', release: '2003-02-22'}, 
    {title: 'Indiana Jhones', release: '2009-01-09'}, 
    {title: 'Jurassic Park', release: '2007-04-13'},
    {title: 'Iron man', release: '2012-12-18'},
    {title: 'Spider man', release: '2017-03-07'}
]

function hasSomeWord(element){
    const year = element.release.split('-')[0]
    return year > 2005 && year < 2010
}
const found = movies.find(hasSomeWord)
console.log(found)

 

* 연습과제 3

const movies = [
    {title: 'Harry Potter', release: '2003-02-22'}, 
    {title: 'Indiana Jhones', release: '2009-01-09'}, 
    {title: 'Jurassic Park', release: '2007-04-13'},
    {title: 'Iron man', release: '2012-12-18'},
    {title: 'Spider man', release: '2017-03-07'}
]

function hasSomeWord(element){
    return element.title.includes('man')
}
const found = movies.find(hasSomeWord)
console.log(found)

 

* 연습과제 4

const movies = [
    {title: 'Harry Potter', release: '2003-02-22'}, 
    {title: 'Indiana Jhones', release: '2009-01-09'}, 
    {title: 'Jurassic Park', release: '2007-04-13'},
    {title: 'Iron man', release: '2012-12-18'},
    {title: 'Spider man', release: '2017-03-07'}
]

function hasSomeWord(element){
    return element.release.split('-')[0] < 2010 && element.title.startsWith('J')
}
const found = movies.find(hasSomeWord)
console.log(found)

 

* 연습과제 5

const words = [
    'abc',
    'animal',
    'fruit',
    'abba',
    'abcba',
    'location',
    'radar',
    'madam',
    'mario',
    'level'
]

for(let word of words){
    if(word.indexOf('a') !== -1){
        console.log(word)
    }
}

 

* 연습과제 6

const API_URL = 'http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline' 

fetch(API_URL)
.then(function(res){
    return res.json()
})
.then(function(products){
    // console.log(products)

    // 조건에 맞는 상품을 검색하는 코드 구현하기

    for(let product of products){
        if(product.product_type === 'mascara' && parseInt(product.price) < 10){
            console.log(product)
        }
    }
})

 

* 연습과제 7

해답 1

const API_URL = 'http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline' 

fetch(API_URL)
.then(function(res){
    return res.json()
})
.then(function(products){
    // console.log(products)

    // 조건에 맞는 상품을 검색하는 코드 구현하기

    for(let product of products){
        if(product.product_type === 'lipstick' && product.rating > 4 && product.rating < 5){
            console.log(product)
        }
    }
})

해답2

const API_URL = 'http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline' 


function checkConditions(product){
    return product.product_type === 'lipstick' && product.rating > 4 && product.rating < 5
}

fetch(API_URL)
.then(function(res){
    return res.json()
})
.then(function(products){
    // console.log(products)

    // 조건에 맞는 상품을 검색하는 코드 구현하기

    const searchedProducts = products.filter(checkConditions)
    console.log(searchedProducts)
    
})

 

* 연습과제 8

const friends = [
    {name: 'victoria', age: 13, city: 'seoul'},
    {name: 'sun', age: 34, city: 'busan'},
    {name: 'johseb', age: 25, city: 'busan'},
    {name: 'syleemomo', age: 9, city: 'seoul'},
    {name: 'hannah', age: 41, city: 'daegu'},
    {name: 'shara', age: 37, city: 'seoul'},
    {name: 'martin', age: 28, city: 'daegu'},
    {name: 'gorgia', age: 39, city: 'seoul'},
    {name: 'nana', age: 24, city: 'busan'},
    {name: 'dannel', age: 19, city: 'seoul'},
]

function isRight(friend){
    return friend.city === 'seoul' && friend.age < 30
}

const friendsFiltered = friends.filter(isRight)
console.log(friendsFiltered)

 

* 연습과제 9

const friends = [
  {name: 'victoria', age: 13, city: 'seoul'},
  {name: 'sun', age: 34, city: 'busan'},
  {name: 'johseb', age: 25, city: 'busan'},
  {name: 'syleemomo', age: 9, city: 'seoul'},
  {name: 'hannah', age: 41, city: 'daegu'},
  {name: 'shara', age: 37, city: 'seoul'},
  {name: 'martin', age: 28, city: 'daegu'},
  {name: 'gorgia', age: 39, city: 'seoul'},
  {name: 'nana', age: 24, city: 'busan'},
  {name: 'dannel', age: 19, city: 'seoul'},
]

// 구현하기
const counts = {'seoul':0, 'busan':0, 'daegu':0}
friends.forEach(function(friend){
  counts[friend.city]++
})

for(let city in counts){
  console.log(`${city} : ${counts[city]}`)
}
const friends = [
  {name: 'victoria', age: 13, city: 'seoul'},
  {name: 'sun', age: 34, city: 'busan'},
  {name: 'johseb', age: 25, city: 'busan'},
  {name: 'syleemomo', age: 9, city: 'seoul'},
  {name: 'hannah', age: 41, city: 'daegu'},
  {name: 'shara', age: 37, city: 'seoul'},
  {name: 'martin', age: 28, city: 'daegu'},
  {name: 'gorgia', age: 39, city: 'seoul'},
  {name: 'nana', age: 24, city: 'busan'},
  {name: 'dannel', age: 19, city: 'seoul'},
]

// 구현하기
const counts = [0, 0, 0]
friends.forEach(function(friend){
  switch(friend.city){
    case 'seoul':
      counts[0]++
      break;
    case 'busan':
      counts[1]++
      break;
    case 'daegu':
      counts[2]++
      break;
  }
})

console.log('seoul : ', counts[0])
console.log('busan : ', counts[1])
console.log('daegu : ', counts[2])
const friends = [
    {name: 'victoria', age: 13, city: 'seoul'},
    {name: 'sun', age: 34, city: 'busan'},
    {name: 'johseb', age: 25, city: 'busan'},
    {name: 'syleemomo', age: 9, city: 'seoul'},
    {name: 'hannah', age: 41, city: 'daegu'},
    {name: 'shara', age: 37, city: 'seoul'},
    {name: 'martin', age: 28, city: 'daegu'},
    {name: 'gorgia', age: 39, city: 'seoul'},
    {name: 'nana', age: 24, city: 'busan'},
    {name: 'dannel', age: 19, city: 'seoul'},
]

const classifiedByCity = {}

function classify(friend){
    if(!classifiedByCity[friend.city]){
        classifiedByCity[friend.city] = 0
    }
    classifiedByCity[friend.city]++
}

friends.forEach(classify)

for(let prop in classifiedByCity){
    console.log(prop, ':', classifiedByCity[prop])
}
const friends = [
  {name: 'victoria', age: 13, city: 'seoul'},
  {name: 'sun', age: 34, city: 'busan'},
  {name: 'johseb', age: 25, city: 'busan'},
  {name: 'syleemomo', age: 9, city: 'seoul'},
  {name: 'hannah', age: 41, city: 'daegu'},
  {name: 'shara', age: 37, city: 'seoul'},
  {name: 'martin', age: 28, city: 'daegu'},
  {name: 'gorgia', age: 39, city: 'seoul'},
  {name: 'nana', age: 24, city: 'busan'},
  {name: 'dannel', age: 19, city: 'seoul'},
]

const classifiedByCity = {}

function classify(friend){
  if(!classifiedByCity[friend.city]){ // 프로퍼티가 존재하지 않으면 해당 프로퍼티의 값을 0 으로 초기화하기
      classifiedByCity[friend.city] = 0
  }
  classifiedByCity[friend.city]++ // 해당되는 도시의 카운트 증가하기 
}

friends.forEach(classify)

console.log(classifiedByCity)

Object.keys(classifiedByCity) // 도시를 의미하는 프로퍼티만 추출하기 
.sort() // 도시 정렬하기 
.forEach( city => console.log(city, ':', classifiedByCity[city])) // 정렬된 도시를 이용하여 해당 도시의 빈도수 조회하기
let friends = [
  {name: 'victoria', age: 13, city: 'seoul'},
  {name: 'sun', age: 34, city: 'busan'},
  {name: 'johseb', age: 25, city: 'busan'},
  {name: 'syleemomo', age: 9, city: 'seoul'},
  {name: 'hannah', age: 41, city: 'daegu'},
  {name: 'shara', age: 37, city: 'seoul'},
  {name: 'martin', age: 28, city: 'daegu'},
  {name: 'gorgia', age: 39, city: 'seoul'},
  {name: 'nana', age: 24, city: 'busan'},
  {name: 'dannel', age: 19, city: 'seoul'},
]

const classifiedByCity = friends
.reduce( (a, friend) => { if(!a[friend.city]) a[friend.city] = 0; a[friend.city]++; return a }, {})

for(let prop in classifiedByCity){
  console.log(prop, ':', classifiedByCity[prop])
}

 

* 연습과제 10

const friends = [
    {name: 'victoria', age: 13, city: 'seoul'},
    {name: 'sun', age: 34, city: 'busan'},
    {name: 'johseb', age: 25, city: 'busan'},
    {name: 'syleemomo', age: 9, city: 'seoul'},
    {name: 'hannah', age: 41, city: 'daegu'},
    {name: 'shara', age: 37, city: 'seoul'},
    {name: 'martin', age: 28, city: 'daegu'},
    {name: 'gorgia', age: 39, city: 'seoul'},
    {name: 'nana', age: 24, city: 'busan'},
    {name: 'dannel', age: 19, city: 'seoul'},
]

function isRight(friend){
    return friend.age >= 40
}

console.log(friends.some(isRight))

 

* 연습과제 11

const users = [
    {name: 'victoria', age: 13, city: 'seoul', email: 'victoria@gmail.com'},
    {name: 'sun', age: 34, city: 'busan', email: 'sun@gmail.com'},
    {name: 'johseb', age: 25, city: 'busan', email: 'johseb@gmail'}, // 탈락
    {name: 'syleemomo', age: 9.23, city: 'seoul', email: 'syleemomo@nate.com'}, // 탈락
    {name: 'hannah', age: 41, city: 'daegu', email: 'hannah0923*gmail.com'}, // 탈락
    {name: 'shara', age: 37, city: 'seoul', email: 'shara@gmail.com'},
    {name: 'martin', age: -34, city: 'daegu', email: 'martin@gmail.com'}, // 탈락
    {name: 'gorgia', age: 39, city: 'seoul',  email: 'gorgia@gmail.com'},
    {name: 'nana', age: 24, city: 'busan', email: 'nana@gmail.com'},
    {name: 'dannel', age: 19, city: 'seoul', email: 'dannel@gmail.com'},
]

let filteredUsers = null

function ageIsValid(user){
    return user.age > 0 && parseInt(user.age) === user.age
}

function emailIsValid(user){
    return user.email.indexOf('@') > -1 && user.email.indexOf('.com') > -1
}


filteredUsers = users.filter(ageIsValid)
filteredUsers = filteredUsers.filter(emailIsValid)
console.log(filteredUsers)
const users = [
  {name: 'victoria', age: 13, city: 'seoul', email: 'victoria@gmail.com'},
  {name: 'sun', age: 34, city: 'busan', email: 'sun@gmail.com'},
  {name: 'johseb', age: 25, city: 'busan', email: 'johseb@gmail'}, // 탈락
  {name: 'syleemomo', age: 9.23, city: 'seoul', email: 'syleemomo@nate.com'}, // 탈락
  {name: 'hannah', age: 41, city: 'daegu', email: 'hannah0923*gmail.com'}, // 탈락
  {name: 'shara', age: 37, city: 'seoul', email: 'shara@gmail.com'},
  {name: 'martin', age: -34, city: 'daegu', email: 'martin@gmail.com'}, // 탈락
  {name: 'gorgia', age: 39, city: 'seoul',  email: 'gorgia@gmail.com'},
  {name: 'nana', age: 24, city: 'busan', email: 'nana@gmail.com'},
  {name: 'dannel', age: 19, city: 'seoul', email: 'dannel@gmail.com'},
]

let filteredUsers = null

function ageIsValid(user){
  return user.age > 0 && parseInt(user.age) === user.age
}

function emailIsValid(user){
  return user.email.indexOf('@') > -1 && user.email.indexOf('.com') > -1
}


const usersFiltered = users
.filter(ageIsValid)
.filter(emailIsValid)

console.log(usersFiltered)

함수(메서드)체이닝을 이용하여 filter 메서드를 연속적으로 사용해도 된다. 왜냐하면 filter 메서드는 필터링된 새로운 배열을 반환하기 때문이다. 

 

* 연습과제 12

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>자바스크립트 연습</title>
    <link rel='stylesheet' href='style.css'/>
</head>
<body>
    <div id="root"></div>
    <script src="app.js"></script>
</body>
</html>
#root{
    width: 60%;
    margin: 100px auto;
    
    display: flex;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
}
.product{
    flex: 200px;
    height: 500px;
    box-shadow: 1px 1px 5px 5px peru;
    color: white;
    background: peru;
    margin: 10px;
    overflow: hidden;
}
.product-img{
    width: 100%;
    height: 180px;
    overflow: hidden;
}
.product-img img{
    width: 100%;
    height: 100%;
}
.product-name{
    font-weight: bold;
    font-size: 1.1rem;
    text-align: center;
}
.product-description{
    font-weight: 400;
    font-size: 0.9rem;
    text-align: center;
    margin-top: 15px;
}
const API_URL = 'http://makeup-api.herokuapp.com/api/v1/products.json?brand=maybelline' 

function buildElement(product){
    const item = document.createElement('div')
    item.className = 'product'

    item.innerHTML = `
                      <div class='product-img'><img src=${product.image_link} alt=${product.name}/></div>
                      <div class='product-name'>${product.name} ($${product.price})</div>
                      <div class='product-description'>${product.description}</div>
                  `
    return item
}

function displayProduct(product){
    console.log(product)
    const rootDiv = document.getElementById('root')
    rootDiv.appendChild(product)
}

fetch(API_URL)
.then(function(res){
    return res.json()
})
.then(function(products){
    console.log(products)

    const productsRefined = products.map(buildElement)
    console.log(productsRefined)

    productsRefined.forEach(displayProduct)

    // 조건에 맞는 상품을 검색하는 코드 구현하기
})
728x90