상세 컨텐츠

본문 제목

[Javascript]배열에서 찾고 싶은 게 있을 때 (every, some, find, findIndex)

Javascript

by stayhungri 2022. 5. 12. 22:48

본문

배열에 있는 요소 중 하나라도 해당 조건을 만족하는게 있는지 알고 싶을 때

some

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/some

const array = [1, 2, 3, 4, 5];

const even = (val) => val % 2 === 0;
console.log(array.some(even));
// true

const found = (val) => val % 6 === 0;
console.log(array.some(found));
// false

 

 

배열에 있는 모든 요소가 해당 조건을 만족하는지 알고 싶을 때

every

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/every

const array = [1, 2, 3, 4, 5];

const isBelowThreshold = (val) => val < 6;
console.log(array.every(isBelowThreshold));
// true

const isBelowThreshold = (val) => val < 4;
console.log(array.every(isBelowThreshold));
// false

 

배열에 있는 요소 중 해당 조건을 만족하는 첫 번째 요소를 반환받고 싶을 때

find

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

const array = [1, 2, 3, 4, 5];

const found = array.find(val => val > 3);
console.log(found);
// 4


const found2 = array.find(val => val > 5);
console.log(found2);
// undefined

 

배열에 있는 요소 중 해당 조건을 만족하는 첫 번째 요소의 인덱스를 반환받고 싶을 때

findIndex

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/findIndex

const array = [1, 2, 3, 4, 5];

const found = array.findIndex(val => val > 3);
console.log(found);
// 3

const found2 = array.find(val => val > 5);
console.log(found2);

 

 

관련글 더보기