const students = [
{ name: "A", score: 90 },
{ name: "B", score: 85 },
{ name: "C", score: 75 },
{ name: "D", score: 95 },
{ name: "E", score: 60 }
] // key, value값으로 학생들의 이름과 점수를 배열로 생성
const excellentStudents = [] // 조건에 맞는 요소를 집어넣기 위한 빈 배열
const excludedStudents = []
const completedStudents = []
for (let i = 0; i < students.length; i++) {
const score = students[i].score // for문으로 students배열의 value값을 변수로 설정
if (score >= 80) {
excellentStudents.push(students[i]) // 조건에 맞는 students의 요소를 정해진 빈 배열에 push
} else {
excludedStudents.push(students[i])
}
const completed = students.splice(i, 1) // students배열에 splice메서드를 이용해서 i라는 인덱스 값을 확정
completedStudents.push(completed[i]) // splice메서드를 통해서 삭제되어 반환되는 배열을 빈 배열로 push
i-- // 순차적으로 배열을 선택할 수 있게 i--를 통해서 for문을 반복할 때 마다 i값이 늘어나지않게
}
console.log("배정 안된 학생들:", students) // 빈 배열이 출력
console.log("우수 학생들:", excellentStudents) // 점수가 80점 이상인 학생들만 출력
console.log("보충 학생들:", excludedStudents) // 점수가 80점 미만인 학생들만 출력
console.log("배정 완료된 학생들:", completedStudents) // 원본 배열에서 삭제되어 반환된 배열
댓글