Ted's Codding study
장바구니 리스트 (배열의 push, forEach, findIndex, filter 활용) 본문
JavaScript
장바구니 리스트 (배열의 push, forEach, findIndex, filter 활용) Ted93 2024. 5. 10. 18:19
콘솔에 찍어보는 초간단 장바구니 리스트 프로젝트
1. 장바구니 리스트를 담을 carts 배열 생성
let carts = [];
2. addCart 함수 생성
기본 로직
- addCart의 파라미터로는 id, name, price, quantity를 받을 것
- index 변수를 생성 후 carts 배열에 추가하고자 하는 상품의 id가 carts에 있는지 확인 후 할당
- 만약 index가 -1이면, 즉 해당 상품의 id가 존재하지 않는다면 정상적으로 아이템을 추가
- index가 -1이 아니라면, 즉 해당 상품의 id가 이미 존재한다면 가격은 덮어쓰기, 갯수는 추가하는 로직으로 작성할 것임
- 콘솔에 보여주기 위해서 displayCart() 함수 호출 (아직 만들지 않았음)
function addCart(id, name, price, quantity) {
const index = carts.findIndex((cart) => cart.id === id);
if (index === -1) {
carts.push({ id, name, price, quantity });
} else {
carts[index].price = price;
carts[index].quantity += quantity;
}
displayCarts();
}
3. displayCarts 함수 생성
기본 로직
- 콘솔에 계속 출력을 해볼테니 먼저 '장바구니 목록: ‘ 이라는 내용을 출력
- carts 배열에 forEach를 활용해서 콘솔에 아래와 같은 양식으로 출력
- 1: 사과 - 5000원, 수량: 4개
- 2: 바나나 - 2000원, 수량: 7개
function displayCarts() {
console.log('장바구니 목록: ');
carts.forEach((cart) => {
console.log(
`${cart.id}: ${cart.name} - ${cart.price}원, 수량: ${cart.quantity}개`
);
});
}
displayCarts를 구현 했으니 addCart를 활용해서 아래 내용을 추가해보면
addCart(1, '사과', 1000, 3);
addCart(2, '바나나', 2000, 7);
addCart(3, '딸기', 8000, 12);
콘솔에 출력되는 모습은 아래와 같다
장바구니 목록:
1: 사과 - 1000원, 수량: 3개
2: 바나나 - 2000원, 수량: 7개
3: 딸기 - 8000원, 수량: 12개
여기에 만약 현재 존재하는 1번 사과의 가격과 갯수를 달리 한다면 가격은 5000원으로 업데이트, 갯수는 3개에서 1개가 추가된 4개가 출력될 것이다.
addCart(1, '사과', 5000, 1);
콘솔에 출력되는 모습은 아래와 같다
장바구니 목록:
1: 사과 - 5000원, 수량: 4개
2: 바나나 - 2000원, 수량: 7개
3: 딸기 - 8000원, 수량: 12개
4. removeFromCarts 함수 생성
기본 로직
- 우리는 배열의 filter를 활용할 것
- 삭제하고자 하는 cart를 유일하게 식별할 수 있는 것은 id임
- removeFromCarts 함수에 id를 인자로 받아 제거하고자 하는 id를 제외한 새로운 배열을 생성
- 현재 carts 리스트를 새로운 배열로 재할당
- displayCart함수를 호출
function removeFromCarts(id) {
carts = carts.filter((cart) => cart.id !== id);
displayCarts();
}
지난번 예제에서 deleteTodo는 로직을 떠올렸다면 이번 코드 구현은 매우 쉬웠을 것으로 예상
removeFromCarts를 구현했으니 제거하고자 하는 id값 3을 넣으면
removeFromCarts(3);
콘솔에 출력되는 모습은 아래와 같다
장바구니 목록:
1: 사과 - 5000원, 수량: 4개
2: 바나나 - 2000원, 수량: 7개
5. updateQuantity 생성
기본 로직
- 체크하려는 Todo를 유일하게 식별할 수 있는 것은 id임
- updateQuantity 함수에 id와 quantitiy를 인자로 받을 것
- index 변수를 생성 후 carts 배열에 추가하고자 하는 상품의 id가 carts에 있는지 확인 후 할당
- index가 -1이거나 quantity가 0이라면, 업데이트할 아이템 자체가 존재하지 않다는 말이니 콘솔에 '해당 아이템을 찾을 수 없습니다.’ 를 출력
- index가 -1이 아니면서 그리고 quantity가 0이 아니라면, 즉 else 조건에는 현재 갯수를 인자에 넣어준 갯수로 재할당
- displayCarts 함수를 호출
function updateQuantity(id, quantity) {
const index = carts.findIndex((cart) => cart.id === id);
if (index === -1 || quantity === 0) {
console.log('해당 아이템을 찾을 수 없습니다.');
} else {
carts[index].quantity = quantity;
}
displayCarts();
}
updateQuantity를 구현했으니 id에 2를 quantity에는 20을 넣어서 호출한다면
updateQuantity(2, 20);
콘솔에 출력되는 모습은 아래와 같다
장바구니 목록:
1: 사과 - 5000원, 수량: 4개
2: 바나나 - 2000원, 수량: 20개
여기에 만약 존재하지 않는 id인 5를 넣고 quantity에는 아무 숫자를 넣는다면
updateQuantity(5, 4);
콘솔에 출력되는 모습은 아래와 같다
해당 아이템을 찾을 수 없습니다.
장바구니 목록:
1: 사과 - 5000원, 수량: 4개
2: 바나나 - 2000원, 수량: 20개
JS 전체 코드
let carts = [];
function addCart(id, name, price, quantity) {
const index = carts.findIndex((cart) => cart.id === id);
if (index === -1) {
carts.push({ id, name, price, quantity });
} else {
carts[index].price = price;
carts[index].quantity += quantity;
}
displayCarts();
}
function displayCarts() {
console.log('장바구니 목록: ');
carts.forEach((cart) => {
console.log(
`${cart.id}: ${cart.name} - ${cart.price}원, 수량: ${cart.quantity}개`
);
});
}
function removeFromCarts(id) {
carts = carts.filter((cart) => cart.id !== id);
displayCarts();
}
function updateQuantity(id, quantity) {
const index = carts.findIndex((cart) => cart.id === id);
if (index === -1 || quantity === 0) {
console.log('해당 아이템을 찾을 수 없습니다.');
} else {
carts[index].quantity = quantity;
}
displayCarts();
}
addCart(1, '사과', 1000, 3);
addCart(2, '바나나', 2000, 7);
addCart(3, '딸기', 8000, 12);
addCart(1, '사과', 5000, 1);
removeFromCarts(3);
updateQuantity(2, 20);
updateQuantity(5, 4);
노션으로 보고 싶다면?
장바구니 리스트 (배열의 push, forEach, findIndex, filter 활용) | Notion
콘솔에 찍어보는 초간단 장바구니 리스트 프로젝트
short-echidna-b16.notion.site