본문 바로가기

개발자

[Javascript] 배열 유용한 10가지 함수 Array API 정리

반응형

 

 

자바스크립트에서 배열(array)은 이름과 인덱스로 참조되는 정렬된 값의 집합으로 정의합니다. 배열을 구성하는 각각의 값을 배열 요소(element)라고 하며, 배열에서의 위치를 가리키는 숫자를 인덱스(index)라고 합니다. 자바스크립트에서 배열의 특징은 다음과 같습니다.

 

1. 배열 요소의 타입이 고정되어 있지 않으므로, 같은 배열에 있는 배열 요소끼리의 타입이 서로 다를 수도 있습니다.

2. 배열 요소의 인덱스가 연속적이지 않아도 되며, 따라서 특정 배열 요소가 비어 있을 수도 있습니다.

3. 자바스크립트에서 배열은 Array 객체로 다뤄집니다.  

 

배열의 생성 자바스크립트에서 배열을 만드는 방법은 다음과 같습니다. 

 

1. var arr = [배열요소1, 배열요소2,...];          // 배열 리터럴을 이용하는 방법

2. var arr = Array(배열요소1, 배열요소2,...);     // Array 객체의 생성자를 이용하는 방법

3. var arr = new Array(배열요소1, 배열요소2,...); // new 연산자를 이용한 Array 객체 생성 방법

 

위의 세 가지 방법은 모두 같은 결과의 배열을 만들어 줍니다. 배열 리터럴은 대괄호([]) 안에 배열 요소를 쉼표로 구분하여 나열하는 방법으로 생성합니다. 예제를 보세요.

 

var arrLit = [1, true, "JavaScript"];             // 배열 리터럴을 이용하는 방법

var arrObj = Array(1, true, "JavaScript");        // Array 객체의 생성자를 이용하는 방법

var arrNewObj = new Array(1, true, "JavaScript"); // new 연산자를 이용한 Array 객체 생성 방법


document.write(arrLit + "<br>");                  // 1,true,JavaScript
document.write(arrObj + "<br>");                  // 1,true,JavaScript 
document.write(arrNewObj);                        // 1,true,JavaScript

 

 

1. 배열을 스트링으로 변환. 스트링을 배열로 변환하는 함수는 2번 참고.

 

{
  const fruits = ["apple", "banana", "orange"];
  
  
  const result = fruits.join(", and ");
  console.log(result);
}

 

 

2. 주어진 string을 배열로 변환

 

// Q2. make an array out of a string
{
  const fruits = 'apple, mango, banana, orange';
    
  const result = fruits.split(','); // 구분자 전달하지 않으면 전체 스트링이 배열 0 위치에 할당
  const result = fruits.split(',', 2); // 앞에 2개만 받을 때
  console.log(result);
}

 

3. 배열을 역순으로 뒤집는다.

 


{
  const array = [1, 2, 3, 4, 5];
  
  const result = array.reverse(); // 배열을 역으로 뒤집고 자신도 역순으로 배열이 됨
  
  console.log(result);
  console.log(array);
}

 

4. 배열에서 앞의 두 요소를 제외한 나머지 배열을 리턴하는 함수

 


{
  const array = [1, 2, 3, 4, 5];
  
  const result = array.splice(0, 2); 
  //인덱스 0부터 두 개를 삭제한 배열을 리턴, 원래 배열은 삭제된 배열을 유지
  
  
  const result = array.slice(2, 5);  
  // start~end 까지 반환, end 넘버는 +1까지
  
  
  console.log(result);
  console.log(array);
}

 

아래는 다음 클래스를 참고한다.

 

class Student {
  constructor(name, age, enrolled, score) {
    this.name = name;
    this.age = age;
    this.enrolled = enrolled;
    this.score = score;
  }
}
const students = [
  new Student('A', 29, true, 45),
  new Student('B', 28, false, 80),
  new Student('C', 30, true, 90),
  new Student('D', 40, false, 66),
  new Student('E', 18, true, 88),
];

 

5. 점수가 90점인 학생을 찾는다. find( )

 


{
  const result = students.find(function(student, index){
  	console.log(student, index);
 });
  
  위 코드를 실행해서 확인하면 5개 반환한다.
  
Student {name: 'A', age: 29, enrolled: true, score: 45} 0
Student {name: 'B', age: 28, enrolled: false, score: 80} 1
Student {name: 'C', age: 30, enrolled: true, score: 90} 2
Student {name: 'D', age: 40, enrolled: false, score: 66} 3
Student {name: 'E', age: 18, enrolled: true, score: 88} 4
  
  다시 개선해서
  
   const result = students.find(function(student, index){
   	  return student.score === 90;
   });
   console.log(result);
   
   결과는
   
   Student {name: 'C', age: 30, enrolled: true, score: 90}
   
  
  위 콜백 함수를 애로우 펑그션으로 다시 작성하면 아래처럼
  
  
  const result = students.find((student) => student.score === 90);
  console.log(result);
  
}

 

6. 등록한 학생들만 출력한다. enrolled 값이 True 값인 학생을 반환

 


{
  const result = students.filter((student) => student.enrolled);
  console.log(result);
}

 

7. 학생들의 점수로만 이루어진 새로운 배열을 리턴

 


// result should be: [45, 80, 90, 66, 88]
{
  const result = students.map((student) => student.score);
  console.log(result);
}

 

8. 학생 점수가 50점 이하가 있는지 없는지 결과를 리턴

 


{
  console.clear();
  const result = students.some((student) => student.score < 50);
  console.log(result);
  
  결과: true

  //모든 학생이 50보다 높으면 true
  const result2 = !students.every((student) => student.score >= 50);
  console.log(result2);
  
  결과: false
}

 

9. 모든 학생 점수의 평균을 구한다.

 

// 배열 요소값을 누적하여 전달

{
  const result = students.reduce((prev, curr) => prev + curr.score, 0);
  console.log(result / students.length);
}

 

 

10. 학생들 점수를 스트링으로 만든다.,

 


// result should be: '45, 80, 90, 66, 88'
{
  const result = students
    .map((student) => student.score)
    .filter((score) => score >= 50)
    .join();
  console.log(result);
}

 

 

11. 학생들 점수를 오름차순으로 정령

 



// result should be: '45, 66, 80, 88, 90'
{
  const result = students
    .map((student) => student.score)
    .sort((a, b) => b - a)
    .join();
  console.log(result);
}

 

 

 

 

 

반응형

캐어랩 고객 지원

취업, 창업의 막막함, 외주 관리, 제품 부재!

당신의 고민은 무엇입니까? 현실과 동떨어진 교육, 실패만 반복하는 외주 계약, 아이디어는 있지만 구현할 기술이 없는 막막함.

우리는 알고 있습니다. 문제의 원인은 '명확한 학습, 실전 경험과 신뢰할 수 있는 기술력의 부재'에서 시작됩니다.

이제 고민을 멈추고, 캐어랩을 만나세요!

코딩(펌웨어), 전자부품과 디지털 회로설계, PCB 설계 제작, 고객(시장/수출) 발굴과 마케팅 전략으로 당신을 지원합니다.

제품 설계의 고수는 성공이 만든 게 아니라 실패가 만듭니다. 아이디어를 양산 가능한 제품으로!

귀사의 제품을 만드세요. 교육과 개발 실적으로 신뢰할 수 있는 파트너를 확보하세요.

지난 30년 여정, 캐어랩이 얻은 모든 것을 함께 나누고 싶습니다.

카카오 채널 추가하기

카톡 채팅방에서 무엇이든 물어보세요

귀사가 성공하기까지의 긴 고난의 시간을 캐어랩과 함께 하세요.

캐어랩 온라인 채널 바로가기

캐어랩