본문 바로가기

WEB개발/JS

[WEB개발] JS 유용한 Array 함수

1)  map

(keyword:map)

 

array.map(callback(currentValue, index, array))

 

 

  • 파라미터:
    • callback: 배열의 각 요소에 대해 호출되는 함수입니다. 이 함수는 다음과 같은 인자를 받습니다:
      • currentValue (필수): 현재 처리 중인 배열 요소.
      • index (선택): 현재 처리 중인 배열 요소의 인덱스.
      • array (선택): map 메서드를 호출한 배열.
  • 반환값: 변형된 요소들로 구성된 새로운 배열.

 

var arr = ["value1", "value2", "value3"];
var newArr = Array.prototype.map.call(arr, function (ele, idx, arrobj) {
	ele = ele + "_modify";
	console.log(ele);
	return ele
});

 

 

2) filter

(keyword:filter)

 

array.filter(callback(currentValue, index, array))

 

  • 파라미터:
    • callback: 배열의 각 요소에 대해 호출되는 함수입니다. 이 함수는 다음과 같은 인자를 받습니다:
      • currentValue (필수): 현재 처리 중인 배열 요소.
      • index (선택): 현재 처리 중인 배열 요소의 인덱스.
      • array (선택): filter 메서드를 호출한 배열.
  • 반환값: 조건을 만족하는 요소들로 구성된 새로운 배열. 조건을 만족하지 않는 요소는 포함되지 않습니다.

 

const people = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 17 },
    { name: "Charlie", age: 30 },
];
const adults = people.filter((person) => person.age >= 18);

console.log(adults);
// [ { name: 'Alice', age: 25 }, { name: 'Charlie', age: 30 } ]

 

 

3) foreach

(keyword:foreach)

 

array.forEach(callback(currentValue, index, array))

 

  • 파라미터:
    • callback: 배열의 각 요소에 대해 호출되는 함수입니다. 이 함수는 다음과 같은 인자를 받습니다:
      • currentValue (필수): 현재 처리 중인 배열 요소.
      • index (선택): 현재 처리 중인 배열 요소의 인덱스.
      • array (선택): forEach 메서드를 호출한 배열.
  • 반환값: undefined. forEach는 값을 반환하지 않습니다.

 

const people = [
    { name: "Alice", age: 25 },
    { name: "Bob", age: 30 },
    { name: "Charlie", age: 35 },
];
people.forEach((person) => (person.age += 1));

console.log(people);
// [ { name: 'Alice', age: 26 }, { name: 'Bob', age: 31 }, { name: 'Charlie', age: 36 } ]

 

 

4) reduce

(keyword:reduce)

 

array.reduce(callback(accumulator, currentValue, currentIndex, array), initialValue);

 

 

  • callback: 배열의 각 요소에 대해 호출되는 함수. 이 함수는 4가지 인자를 받습니다:
    • accumulator: 이전 함수 호출에서 반환된 값. initialValue를 설정하지 않으면 배열의 첫 번째 요소가 기본값이 됩니다.
    • currentValue: 현재 처리 중인 배열 요소.
    • currentIndex: 현재 처리 중인 배열 요소의 인덱스 (optional).
    • array: reduce를 호출한 배열 (optional).
  • initialValue (선택 사항): 누산기의 초기값을 지정합니다. 설정하지 않으면 배열의 첫 번째 요소가 사용됩니다.

 

 

배열 내 중복 요소 개수 세기

 

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

const count = fruits.reduce((accumulator, fruit) => {
  accumulator[fruit] = (accumulator[fruit] || 0) + 1;
  return accumulator;
}, {});

console.log(count); 
// { apple: 3, banana: 2, orange: 1 }

 

 

5)  every() (  <> some ) 

(keyword:every, keyword:some)


메서드는 배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트합니다. Boolean 값을 반환합니다.

 

array.every(callback(currentValue, index, array))

 

array.every(callback(currentValue, index, array))
  • callback: 각 요소에 대해 호출되는 함수.
    • currentValue: 현재 처리 중인 요소.
    • index: 현재 요소의 인덱스 (optional).
    • array: 호출된 배열 (optional).

 

const numbers = [2, 4, 6, 8];
const allEven = numbers.every(num => num % 2 === 0);

console.log(allEven);  // true

 

5) find()

(keyword:find)

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소 을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

 

array.find(callback(currentValue, index, array))

 

 

callback: 각 요소에 대해 호출되는 함수.

  • currentValue: 현재 처리 중인 배열의 요소.
  • index: 현재 요소의 인덱스 (optional).
  • array: find를 호출한 배열 (optional).

 

const users = [
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 30 },
  { name: 'Charlie', age: 35 }
];

const user = users.find(user => user.age > 30);

console.log(user);  // { name: 'Charlie', age: 35 }

 

6) sort()

(keyword:sort)

sort() 메서드는 배열의 요소를 적절한 위치에 정렬한 후 그 배열을 반환합니다. 정렬은 stable sort가 아닐 수 있습니다. 기본 정렬 순서는 문자열의 유니코드 코드 포인트를 따릅니다.

 

array.sort([compareFunction])

 

 

compareFunction (optional): 정렬 순서를 정의하는 함수.

  • 두 개의 요소를 비교하고 다음의 값을 반환합니다:
    • 0보다 작은 값: a가 b보다 앞에 오도록 정렬.
    • 0: 순서를 변경하지 않음.
    • 0보다 큰 값: b가 a보다 앞에 오도록 정렬.

 

const fruits = ['banana', 'apple', 'cherry'];
fruits.sort();

console.log(fruits);  // ['apple', 'banana', 'cherry']

'WEB개발 > JS' 카테고리의 다른 글

[JS] Async, Await, Fetch, PromiseAll  (0) 2023.03.06
[JS, JAVA] 정규식  (0) 2022.06.13
[JS] JS의 비동기 작업 ( = promise)  (0) 2021.06.24
[JS] Engine, Event Loop  (0) 2021.06.24
[JS] input(inputmode, event, pattern)  (0) 2021.06.24