배열 정리.js(20211229)

홍륜건·2021년 12월 29일
0

오늘은 자바스크립트

배열 검색

1.배열.indexOf(검색할 요소, 검색 시작 위치)

검색할 요소를 찾으면 인데스값을 반환하고, 검색에 실패하면 -1을 반환한다.

const animals = ['lion', 'tiger','cat','dog','pig','cat']
const searchCat = animals.indexOf('cat')
console.log(search) //2

const searchCat3 = animals.indexOf('cat',3)
//시작위치를 추가하면 인덱스 3번째 이후부터 검색한다.

const searchGiraffe = animals.indexOf('giraffe')

console.log(search) //giraffe가 배열에 없으므로 -1을 반환

만약 cat이라는 동물 이름이 여러번 존재할때, 모두 검색하려면 아래와 같이 하면 된다.

const animals = ['lion', 'tiger', 'cat', 'dog', 'pig', 'cat', 'giraffe', 'duck', 'cat']
const searchCat = 'cat'
const searchedIndexes = [] //찾은 고양이 index를 저장할 배열

let foundIndex = animals.indexOf(searchCat) //indexOf로 고양이를 찾는다. 
while(foundIndex != -1){ //indexOf가 더 이상 값을 찾아내지 못해 -1을 반환하면 루프 종료
	searchedIndexes.push(foundIndex) //찾은 index를 배열에 집어넣는다. 
    foundIndex = animals.indexOf(searchCat,foundIndex+1) 
    //찾은 index에서 +1한 다음 index부터 검색한다. 

2.배열.lastIndexOf(검색할 요소, 검색 시작 위치)

배열의 lastIndexOf 메서드는 indexOf와 작동방식은 같지만 검색시작 위치에서 반대로 검색한다.

3.배열.find(판별함수)

functio 판별함수명(배열요소, 인덱스, 배열){
	return 판별조건
    }

배열의 find메서드는 인자로 '판별함수'가 들어간다. 판별함수는 콜백함수로써 반복문에서 배열요소를 조회하듯 배열요소를 꺼내서 판별조건을 검사한다.
판별조건을 처음으로 만족하는 배열요소의 값을 반환한다. 만약 충족하는 요소가 없다면 undefined를 반환한다.

const fruits = ['apple', 'banana', 'orange', 'watermelon']

function longest(element, index, fruits){
    return element.length > 6
}
const found = fruits.find(longest)

console.log(found)

4.배열findIndex(판별함수)

findIndex()함수는 find()와 용법은 동일하나, index를 반환한다.

5.배열.includes(검색할 값)

includes메서드는 배열의 인자로 주어진 값을 배열요소로 가지고 있는지 판단한다.
반환값은 ture나 false인 논리값이다.

const seasons = ['spring', 'summer', 'autumn', 'winter']

console.log(seasons.includes('summer')) // true
console.log(seasons.includes('cat')) // false

문자열도 배열이므로 includes메서드를 사용할 수 있다.

const title = 'Haprry potter'

console.log(title.includes('potter')) // true

6.배열.filter(판별함수)

filter()의 인자로 판별함수가 들어간다. 콜백함수이고 배열요소를 검사하여 조건을 만족하는 요소들을 '새로운 배열'로 반환한다.

const words = ['car', 'paper', 'mobile', 'computer', 'school', 'sun', 'house']

function isShort(word){
	return word.length<5
 	}
const wordFiltered = words.filter(isShort)

console.log(wordsFilterd)

7.배열.some(판별함수)

some()의 인자로 판별함수가 들어간다. 콜백함수이고 배열요소중 '어느 하나'라도 조건을 만족하면 true를 반환한다. 빈 배열은 무조건 false를 반환한다.

const numbers = [32, 6, 4, 13, 9, 57]

function isMultiply(element){
	return element %3 === 0
   	}
console.log(numbers.some(isMultiply)

8.배열.every(판별함수)

every()는 some()과 비슷하지만 '모든 요소'가 만족해야 true를 반환한다. 역시 빈 배열은 false를 반환한다.

const numbers = [32, 6, 4, 13, 9, 57]

function isMultiply(element){
	return element %3 === 0
   	}
console.log(numbers.every(isMultiply)
profile
초보 개발자 지망생

0개의 댓글