[JavaScript] 배열 함수

박준석·2024년 4월 5일

JavaScript

목록 보기
9/10
post-thumbnail

배열함수

배열함수에 대해 다뤄 볼 생각이다.

forEach

기존 for문을 대체할 수 있다.

  • for문
let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

for(let i=0; i<names.length; i++){
    console.log(names[i]);
}
  • forEach
let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

names.forEach(value => console.log(value));

map

배열의 각 원소별로 지정된 함수를 실행한 결과로 구성된 새로운 배열을 반환한다.

let ceoList=[
  	{name:"rina", age:23, ceo:true},
	{name:"park", age:40, ceo:true},
	{name:"kim", age:45, ceo:false}
]

let ceoDate = ceoList.map((item)=>{ 
    return item.name;   
});
console.log(ceoDate);

filter

지정된 함수의 결과 값을 ture로 만드는 원소들로만 구성된 별도의 배열을 반환한다.

let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

let ceoList=[{name:"rina", age:23, ceo:true},
{name:"park", age:40, ceo:true},
{name:"kim", age:45, ceo:false}
]

let ceoDate2 = ceoList.filter((item)=>{ 
    return item.age==23; // 나이가 23살인 사람만 필터링 해줘
});
console.log(ceoDate2);

let ceoDate3 = names.filter((item)=>{ 
    return item.startsWith("L"); //첫글자가 L로 시작하는 것 다 필터링 해줘.
});
console.log(ceoDate3);

some

지정된 함수의 결과가 ture일 때까지 배열의 각 원소를 반복한다.

let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

let ceoDate4 = names.some((item)=>{ 
    return item.startsWith("L"); //첫글자가 L로 시작하는 것이 하나라도 있나?
});
console.log("L로 시작하는 : ",ceoDate4); // true

every

배열의 모든 요소가 제공한 함수로 구현된 테스트를 통과하는지 테스트한다.

let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

let ceoDate4 = names.some((item)=>{ 
    return item.startsWith("L"); //첫글자가 L로 시작하는 것이 하나라도 있나?
});
console.log("L로 시작하는 : ",ceoDate4); // true

find

원하는 요소를 새 배열로 추출한다.

let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

let ceoDate6 = names.find((item)=>{ 
    return item.startsWith("L"); //첫글자가 L로 시작하는 첫번째 아이템
});
console.log(ceoDate6); //Leo

findIndex

원하는 요소의 인덱스 번호를 추출한다.

let names = ["Leo",
"Lio",
"Lee",
"Luna"
];

let ceoDate7 = names.findIndex((item)=>{ 
    return item.startsWith("Luna"); //Luna에 인덱스 번호.
});
console.log(ceoDate7);// 4

reduce

반복해서 배열의 값을 반환하는데 이것이 누적된다. 인자로는 콜백함수와 initValue가 오는데 필수사항이다.

콜백함수 안의 인자는 처음값(initalValue), 현재값(currentValue), 현재 인덱스(currentIndex), array로 총 4개다.

const arrList = [1, 2, 3, 4, 5 ];
const newList = arrList.reduce((prev, curr, curI, arr) => (prev + curr), 0);
console.log(newList);	//15

sort

배열의 순서를 정렬한다.

const numArr = [5, 4, 3, 2, 1];
numArr.sort();
console.log(numArr);		// [1, 2, 3, 4, 5];

숫자 순서대로 나열이 된다. 하지만 숫자의 크기대로 나열하는 것은 아니다.

const numArrStrange = [10, 24, 115, 34, 264];
numArrStrange.sort();
console.log(numArrStrange);	//[10, 115, 24, 264, 34];

위 코드를 보면 [10, 24, 35, 115, 264]가 리턴이 되어야 하는데 이렇게 정렬이 된 이유는 아스키코드 순서이기 때문이다.

해결하는 방법은 다양하다 ab 인자를 넣어 비교를 하면 된다.

var arrNum = [ 10, 24, 115, 34, 264 ] ;
 
let result = arrNum.sort(function(a, b){
	return a - b ;
}) ;
 
console.log( result ) ;		// [10, 24, 34, 115, 264]
profile
느리지만 탄탄한 개발자 1명 빠른 개발자 10명 안부럽다.

0개의 댓글