WebProgramming/JS

[JS] Array 메소드 (map,filter,reduce,find,concat,slice)

2022. 7. 15. 22:01
목차
  1. 1. map()
  2. 2. filter()
  3. 3. reduce()
  4. 4. find()
  5. 4.1 findIndex()
  6. 5. concat()
  7. 6. slice()
  8. 7. forEach()
  9.  

1. map()

; 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환

ex1) numbers의 요소들 각각에 2배를 하여 doubleNumArray에 반환

const numbers = [1,2,3]
const doubleNumArray = numbers.map(num=>num*2)
console.log(doubleNumArray) // [2,4,6]

 

ex2) number의 요소들을 Number화 시키기

const numbers = ['1','2','3']
console.log(numbers.map(Number))

 

ex3) map과 assign을 이용한 예시

let userList = [
  { name: "Mike", age: 30 },
  { name: "Jane", age: 27 },
  { name: "Tom", age: 10 }
];

let newUserList = userList.map((user, index) => {
  return Object.assign({}, user, {
    id: index + 1,
    isAdult: user.age > 19
  });
});
console.log(newUserList);

 

2. filter()

; find와 사용법 동일 / find와 달리, 만족시키는 모든 요소를 배열로 반환

ex1) filter()을 활용한 검색하는 함수

notes={notes.filter((note) =>
	note.text.toLowerCase().includes(searchText)
)}

; notes를 하나씩 꺼내 note에 넣음 -> 각각의 note의 text가 searchText를 포함하고 있으면 notes 배열로 재구성

 

ex2) filter()를 활용한 요소를 삭제하는 함수

const deleteNote = (id) => {
    const newNotes = notes.filter((note) => note.id !== id);
    setNotes(newNotes);
}

; notes를 하나씩 꺼내 note에 넣음 -> 각각의 note의 id가 인수로 받은 id와 일치하지 않는 것들로만 newNotes를 구성

 

ex3) 값이 3이상인 요소 추출

data.filter((it) => it.emotion>=3)

 

3. reduce()

; 누산기가 포함되어 있어, 배열의 각 요소에 대해 함수를 실행하고 누적된 값을 출력할 때 용이

reduce(callback,initialValue)

# initialValue ; callback의 최초 호출에서 첫 번째 인수에 제공되는 값. 제공안할 시 배열의 첫 번째 요소 사용

ex1) 누적합

const array1 = [1, 2, 3, 4];

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
);
// previousValue는 이전까지 계산된 값 / currentValue는 현재 취할 값
console.log(sumWithInitial); // 10

여기서 callback함수는 (previousValue,currentValue)=>previousValue+currentValue 이고 initialValue는 initialValue(0)이다.

 

ex2) 초기값이 10인 누적합

const arr2 = [1, 2, 3, 4, 5];
const result2 = arr2.reduce((acc, cur, idx) => { return acc += cur; }, 10);
console.log(result2);  // 25

 

ex3) 객체배열에서 age가 25보다 큰 요소만으로 배열 구성하기

let userList = [
  { name: "Make", age: 30 },
  { name: "Tom", age: 23 }
];
let result = userList.reduce((prev, cur) => {
  if (cur.age > 25) {
    prev.push(cur.name);
  }
  return prev;
}, []);
console.log(result);

 

4. find()

; 만족시키는 첫 요소 반환. 없을 경우 undefined 반환

array.find((element,index,array)=>{})

ex1) element값이 10보다 크면서, index가 3보다 큰 요소 반환

const array1 = [5, 12, 8, 130, 44];
const found = array1.find((element,index,array) => element > 10 & index>3 );
console.log(found); // 44

array.find(function)

ex2) find()안에 function을 넣어, function을 만족하는 값  반환

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find( ({ name }) => name === 'cherries' );

console.log(result) // { name: 'cherries', quantity: 5 }

 

4.1 findIndex()

; 만족시키는 첫 요소의 index 반환. 없을 경우 -1 반환

array.findIndex((element)=>{})

ex2) findIndex안에 element매게변수를 이용한 화살표함수 넣기

const array1 = [5, 12, 8, 130, 44];
console.log(array1.findIndex(element=>element>13));

 

array.findIndex(function)

ex2) findIndex()안에 function을 넣어, functino 만족하는 값의 index 반환

const array1 = [5, 12, 8, 130, 44];
const isLargeNumber = (element) => element > 13;
console.log(array1.findIndex(isLargeNumber)); // 3

 

5. concat()

; 2개 이상의 배열을 merge할 때 사용

array.concat(array2,array3,...)

ex) array1과 array2를 합친 배열 array3

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];

const array3 = array1.concat(array2);
console.log(array3); // ["a", "b", "c", "d", "e", "f"]

const array4 = [...array1,...array2]
console.log(array4); // ["a", "b", "c", "d", "e", "f"]

// 더 범용적으로 쓸 수 있는 spread를 이용하면 되는데 굳이? spread가 최신 js에서 나온거라 예전에는 concat이 쓰였나보다.

 

6. slice()

; 잘라내, 깊은 복사하여 return

array.slice(end) / array.slice(start,end) / array.slice() ; 깊은 복사 

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice(2)); //["camel", "duck", "elephant"]
console.log(animals.slice(2, -1)); //["camel", "duck"]
console.log(animals.slice()); //["ant", "bison", "camel", "duck", "elephant"]

 

7. forEach()

; 데이터값과 인덱스값을 모두 mapping

let arr = ["Mike", "Tom", "Jane"];
arr.forEach((name, index) => {
  console.log(`${index + 1}번째 이름 ${name}`);
});

 

 

- indexOf(a,b) ; [b]부터 처음 나타나는 a 찾기

- lastIndexOf(a) ; 뒤에서부터 처음 나타나는 a 찾기

- includes(a) ; a를 포함하고 있는지 판별

- join(' ') ; 배열 요소들을 사이에 ' '를 넣어 하나의 문자열로 합쳐줌 / split(' ') ; 하나의 문자열을 ' '을 기준으로 배열요소들로 분리함

- sort(fn) ; fn을 기준으로 정렬

let arr = [24, 8, 5, 13];
// sort는 문자열 기반 정렬이기때문에, 위 요소들의 첫 번째 요소를 기준으로 정렬함
const fn = (a, b) => {
  return a - b;
};
arr.sort(fn);
console.log(arr);
더보기

위처럼 함수를 매번 만드는 것이 번거롭기에, lodash 라이브러리를 사용

_.sortBy(arr)를 사용하면 숫자든, 문자든 원하는 대로 정렬해줌

 

저작자표시 (새창열림)

'WebProgramming > JS' 카테고리의 다른 글

[JavaScript] 한 페이지 정리  (0) 2022.07.26
[JavaScript] Computed Property  (0) 2022.07.26
[JavaScript] Object Methods(assign,keys,values,entries,fromEntries)  (0) 2022.07.26
[JS] JS 라이브러리 (lodash, axios)  (0) 2022.06.30
[TS] 타입 별칭 & Interface  (0) 2022.06.24
[TS] TS의 타입 시스템? & Compliation Context  (0) 2022.06.12
[TS] TypeSCript이란? & 타입  (0) 2022.06.12
[JS] JSON  (0) 2022.06.11
  1. 1. map()
  2. 2. filter()
  3. 3. reduce()
  4. 4. find()
  5. 4.1 findIndex()
  6. 5. concat()
  7. 6. slice()
  8. 7. forEach()
  9.  
'WebProgramming/JS' 카테고리의 다른 글
  • [JavaScript] Computed Property
  • [JavaScript] Object Methods(assign,keys,values,entries,fromEntries)
  • [JS] JS 라이브러리 (lodash, axios)
  • [TS] 타입 별칭 & Interface
피터s
피터s
1년차 프론트엔드 개발자입니다 😣 아직 열심히 배우는 중이에요! 리액트를 하고있어요 :) - gueit214@naver.com - https://github.com/gueit214
피터s
피터의 성장기록
피터s
전체
오늘
어제
  • 분류 전체보기 (200)
    • 코딩 테스트 (25)
      • 프로그래머스 (16)
      • LeetCode (8)
      • 백준 (1)
    • 개발 독서 일지 (1)
    • 기업 분석 (4)
    • 개발 일지 (19)
      • 최신기술 도전기 (1)
      • 에러 처리 (5)
      • 개발 일지 (12)
    • 개발 일상 (36)
      • 개발 회고 (22)
      • 개발 이야기 (12)
      • 개발 서적 (1)
    • 취업 관련 지식 (11)
    • 알고리즘 (17)
    • WebProgramming (84)
      • WebProgramming (8)
      • HTML (5)
      • CSS (8)
      • JS (21)
      • React (40)

블로그 메뉴

  • About
  • 2022년 개발 성장기
  • 앞으로의 계획
  • github
  • 일상 blog

공지사항

인기 글

태그

  • dfs
  • 1일 1커밋 후기
  • LV2
  • 스터디 후기
  • KAKAO BLIND
  • 개발 일상
  • 1년 회고
  • Kakao Tech Internship
  • 카카오
  • lv3
  • 해커톤
  • 반복문
  • 개발 회고
  • 함수
  • Retry
  • 누적합
  • 개발 is life
  • BFS
  • 카카오 채용연계형 인턴십
  • 구름
  • Union-find
  • 구름톤

최근 댓글

최근 글

hELLO · Designed By 정상우.
피터s
[JS] Array 메소드 (map,filter,reduce,find,concat,slice)
상단으로

티스토리툴바

개인정보

  • 티스토리 홈
  • 포럼
  • 로그인

단축키

내 블로그

내 블로그 - 관리자 홈 전환
Q
Q
새 글 쓰기
W
W

블로그 게시글

글 수정 (권한 있는 경우)
E
E
댓글 영역으로 이동
C
C

모든 영역

이 페이지의 URL 복사
S
S
맨 위로 이동
T
T
티스토리 홈 이동
H
H
단축키 안내
Shift + /
⇧ + /

* 단축키는 한글/영문 대소문자로 이용 가능하며, 티스토리 기본 도메인에서만 동작합니다.