기록

기본 함수 정리 (Array)

안녕하세요 청이입니다.

JavaScript Array에서 제공하는 기본 함수에서, 자주 사용되는 것을 간략이 요약 정리 하도록 하겠습니다.

String 기본 함수를 정리하고 나서 보니 상당부분이 유사하게 사용되는것을 알수 있네요

https://blog.naver.com/kw8989/223143170960


배열내 값 반환
Array.at() : at(index)
정수 or 음수의 숫자를 받아 Array에서 값을 찾아 반환 합니다.
정수 : 배열의 앞에서 부터 검색
음수 : 배열의 뒤에서 부터 검색

const array1 = [5, 12, 8, 130, 44];

let index = 2;

console.log(`Using an index of ${index} the item returned is ${array1.at(index)}`);
// Expected output: "Using an index of 2 the item returned is 8"

index = -2;

console.log(`Using an index of $qo{index} item returned is ${array1.at(index)}`);
// Expected output: "Using an index of -2 item returned is 130"

기존에, Array[1] 과 Array.at(1) 은 동일한 결과를 반환 한다, 그런데 왜 at은 필요하게 된걸까?
만약, 배열의 마지막의 값을 반환 받으려면 어떻게 될까?

Array[Array.length -1]
Array.at(-1)

배열 병합
Array.concat()
Array.concat([value1[, value2[, ...[, valueN]]]])
concat은 주어진 배열들을 순차적으로 하나로 병합하여, 새로운 배열을 반환 합니다.

const num1 = [1, 2, 3];
const num2 = [4, 5, 6];
const num3 = [7, 8, 9];

num1.concat(num2, num3);
// 결과: [1, 2, 3, 4, 5, 6, 7, 8, 9]

Array.copyWithin()
Array.copyWithin(target[, start[, end]])
target : 복사한 값을 넣을 위치로 정수 or 음수를 받으며 음수일 경우 배열의 뒤에서부터 계산 합니다.
만약, Array.length 길이와 같거나, 큰 경우 값을 복사하지 않습니다.
또 target이 start보다 뒤라면 복사한 값을, Array.length 길이에 맞춰 자릅니다.

옵션, start : 복사를 시작할 위치( 기본 0 ), 음수 일 경우 배열의 뒷 부분 부터
옵션, end : 복사를 끝낼 위치를 가르키는 인덱스로, 해당 인덱스 전까지 복사하며, 해당 인덱스의 값은 복사하지 않습니다. 기본값 (Array.length)로 배열의 마지막 까지 복사합니다.

[1, 2, 3, 4, 5].copyWithin(-2);
// [1, 2, 3, 1, 2]

[1, 2, 3, 4, 5].copyWithin(0, 3);
// [4, 5, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(0, 3, 4);
// [4, 2, 3, 4, 5]

[1, 2, 3, 4, 5].copyWithin(-2, -3, -1);
// [1, 2, 3, 3, 4]

[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}

// ES2015 TypedArray는 Array의 하위 클래스
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// 아직 ES2015를 사용할 수 없는 환경에서
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

Array.entries()
배열의 각 인덱스에 대한 키/값 쌍을 가지는 새로운 Array Itrator 객체를 반환 합니다.
*Itration : 반복처리 의미로 배열내 요소를 연속적으로 꺼내는 행위를 뜻함
*Itratior Object / Array : 반복처리 의미로 배열내 요소를 연속적으로 꺼내는 행위가는한 객체 또는 배열

const array1 = ['a', 'b', 'c'];

const iterator1 = array1.entries();

console.log(iterator1.next().value);
// Expected output: Array [0, "a"]

console.log(iterator1.next().value);
// Expected output: Array [1, "b"]

for (const element of [, "a"].entries()) {
  console.log(element);
}
// [0, undefined]
// [1, 'a']

Array.every()
배열 안의 모든 요소가 주어진 판별 함수를 통과 하는지 테스트 하며, 결과는Boolean 으로 반환 한다.
배열의 요소중 하나라도 판별 함수를 통과 하지 못하면, 즉시 false 반환

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

element: 배열에서 처리되는 현재 요소 값
index : 현재 요소의 index 값
array : every를 호출한 Array

every의 특성을 이용하면, 배열의 수만큼 반복하면서,
원본배열(every를 호출한 배열)에 값을 변경하되, every의 동작 횟수에 영향을 주지 않는 기능을 구현 할수 있다.

function isBigEnough(element, index, array) {
  return element >= 10;
}
[12, 5, 8, 130, 44].every(isBigEnough);   // false
[12, 54, 18, 130, 44].every(isBigEnough); // true

const isSubset = (array1, array2) => array2.every((element) => array1.includes(element));
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 7, 6])); // true
console.log(isSubset([1, 2, 3, 4, 5, 6, 7], [5, 8, 7])); // false

// ---------------
// 요소 수정
// ---------------
let arr = [1, 2, 3, 4];
arr.every( (elem, index, arr) => {
  arr[index+1] -= 1
  console.log(`[${arr}][${index}] -> ${elem}`)
  return elem < 2
})

// 3회 순회하지만 앞선 2회의 순회는 수정이 일어나지 않습니다.
//
// 1st iteration: [1,1,3,4][0] -> 1
// 2nd iteration: [1,1,2,4][1] -> 1
// 3rd iteration: [1,1,2,3][2] -> 2

// ---------------
// 요소 추가
// ---------------
arr = [1, 2, 3];
arr.every( (elem, index, arr) => {
  arr.push('new')
  console.log(`[${arr}][${index}] -> ${elem}`)
  return elem < 4
})

// 새로운 요소가 추가된 후에도 3회 순회합니다.
//
// 1st iteration: [1, 2, 3, new][0] -> 1
// 2nd iteration: [1, 2, 3, new, new][1] -> 2
// 3rd iteration: [1, 2, 3, new, new, new][2] -> 3

// ---------------
// 요소 삭제
// ---------------
arr = [1, 2, 3, 4];
arr.every( (elem, index, arr) => {
  arr.pop()
  console.log(`[${arr}][${index}] -> ${elem}`)
  return elem < 4
})

// 기존 요소가 `pop()` 됨에 따라 2회만 순회합니다.
//
// 1st iteration: [1,2,3][0] -> 1
// 2nd iteration: [1,2][1] -> 2

Array.fill()
배열의 시작 인덱스부터, 끝 인덱스의 이전 까지 정적인 값 하나로 채웁니다.
반환값 : 수정된 원본 배열

arr.fill(value\[, start\[, end\]\])
const array1 = [1, 2, 3, 4];

// Fill with 0 from position 2 until position 4
console.log(array1.fill(0, 2, 4));
// Expected output: Array [1, 2, 0, 0]

// Fill with 5 from position 1
console.log(array1.fill(5, 1));
// Expected output: Array [1, 5, 5, 5]

console.log(array1.fill(6));
// Expected output: Array [6, 6, 6, 6]

[1, 2, 3].fill(4);               // [4, 4, 4]
[1, 2, 3].fill(4, 1);            // [1, 4, 4]
[1, 2, 3].fill(4, 1, 2);         // [1, 4, 3]
[1, 2, 3].fill(4, 1, 1);         // [1, 2, 3]
[1, 2, 3].fill(4, 3, 3);         // [1, 2, 3]
[1, 2, 3].fill(4, -3, -2);       // [4, 2, 3]
[1, 2, 3].fill(4, NaN, NaN);     // [1, 2, 3]
[1, 2, 3].fill(4, 3, 5);         // [1, 2, 3]
Array(3).fill(4);                // [4, 4, 4]
[].fill.call({ length: 3 }, 4);  // {0: 4, 1: 4, 2: 4, length: 3}

// Objects by reference.
var arr = Array(3).fill({}); // [{}, {}, {}]
arr[0].hi = "hi"; // [{ hi: "hi" }, { hi: "hi" }, { hi: "hi" }]

Array.filter()
주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환.
반환 값 : 배열

arr.filter(callback(element\[, index\[, array\]\])\[, thisArg\])
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

const result = words.filter(word => word.length > 6);

console.log(result);
// Expected output: Array ["exuberant", "destruction", "present"]

var fruits = ['apple', 'banana', 'grapes', 'mango', 'orange'];

/**
 * 검색 조건에 따른 배열 필터링(쿼리)
 */
function filterItems(query) {
  return fruits.filter(function(el) {
      return el.toLowerCase().indexOf(query.toLowerCase()) > -1;
  })
}

console.log(filterItems('ap')); // ['apple', 'grapes']
console.log(filterItems('an')); // ['banana', 'mango', 'orange']

Array.find() =/= Array.findLast()
Array.find() : 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환하며, 없으면 undefined
Array.findLast() : 배열을 역순으로 검사함

값을 찾는 순간 반복을 종료함으로, 필터와 달리 중간에 값을 찾았다면, 불필요한 반복을 줄 일수 있다.
반환 값 : 해당되는 값 (배열 아님)

arr.find(callback\[, thisArg\])
const array1 = [5, 12, 8, 130, 44];

const found = array1.find(element => element > 10);

console.log(found);
// Expected output: 12

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

function findCherries(fruit) {
    return fruit.name === 'cherries';
}

console.log(inventory.find(findCherries)); // { name: 'cherries', quantity: 5 }

Array.findIndex() =/= findLastIndex()
Array.findIndex() : 주어진 판별 함수를 만족하는 첫 번째 요소의 인덱스 값을 반환 합니다. 없으면 -1
findLastIndex() : 배열을 역순으로 검사함

arr.findIndex(callback(element\[, index\[, array\]\])\[, thisArg\])
const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// Expected output: 3

Array.flat()
모든 하위 배열 요소를 지정한 깊이 까지 재귀적으로 이어붙인 새로운 배열을 반환 (중첩 배열 제거 후 병합)
const newArr = arr.flat([depth])

const arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]

const arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

const arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

const arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

const arr5 = [1, 2, , 4, 5];
arr5.flat();
// [1, 2, 4, 5]

Array.flatMap()
주어진 함수를 반복하고, 반환되는 값에 대하여 flat()을 적용한 배열을 반환 한다.
arr.flatMap(callback(currentValue[, index[, array]])[, thisArg])

중요한것은, 이 flat에는 옵션을 지정할수 없다. ( flat 깊이 1 고정 )

let arr1 = [1, 2, 3, 4];

arr1.map(x => [x * 2]);
// [[2], [4], [6], [8]]

arr1.flatMap(x => [x * 2]);
// [2, 4, 6, 8]

// 한 레벨만 평탄화됨
arr1.flatMap(x => [[x * 2]]);
// [[2], [4], [6], [8]]

Array.forEarch()
주어진 함수를 배열 요소 각각에 대해 실행 합니다.

arr.forEach(callback(currentvalue\[, index\[, array\]\])\[, thisArg\])

currentvalue : 현재 처리하는 값
index : 현재 실행되는 배열 요소의 인덱스
array : forEach를 호출한 배열

const array1 = ['a', 'b', 'c'];

array1.forEach(element => console.log(element));

// Expected output: "a"
// Expected output: "b"
// Expected output: "c"

Array.from()
유사 배열객체 (길이를 가지는 객체) 또는 반복 가는한 객체를 얉게 복사 하여 새로운 Array 객체로 반환

Array.from(arrayLike\[, mapFn\[, thisArg\]\])
console.log(Array.from('foo'));
// Expected output: Array ["f", "o", "o"]

console.log(Array.from([1, 2, 3], x => x + x));
// Expected output: Array [2, 4, 6]
function f() {
  return Array.from(arguments);
}

f(1, 2, 3);

// [1, 2, 3]

Array.includes()
배열이 특정 요소를 포함하는가를 판단 한다.
반환값 : Boolean

arr.includes(valueToFind\[, fromIndex\])
const array1 = [1, 2, 3];

console.log(array1.includes(2));
// Expected output: true

const pets = ['cat', 'dog', 'bat'];

console.log(pets.includes('cat'));
// Expected output: true

console.log(pets.includes('at'));
// Expected output: false

includes를 이용해서, 중복 체크를 할떄 간략하게 표현 할수도 있다.

[AUTH_IRB_EVD_TYPE.EVD, AUTH_IRB_EVD_TYPE.EV, AUTH_IRB_EVD_TYPE.E].includes(status.evd),

Array.indexOf() =/= Array.lastIndexOf()
Array.indexOf() : 배열에, 해당 되는 값이 있는지 체크하고 인덱스를 반환 하며, 없으면 -1을 반환 합니다.
Array.lastIndexOf() : 배열을 역순으로 검색 합니다.

모든 값을 순회 하지 않고, 값이 있으면 바로 반복을 종료합니다.

arr.indexOf(searchElement\[, fromIndex\])
const beasts = ['ant', 'bison', 'camel', 'duck', 'bison'];

console.log(beasts.indexOf('bison'));
// Expected output: 1

// Start from index 2
console.log(beasts.indexOf('bison', 2));
// Expected output: 4

console.log(beasts.indexOf('giraffe'));
// Expected output: -1

Array.isArray()
입력된 값이 Array인지 판단 합니다. ( 불리언 값 반환 )

// 모두 true 반환
Array.isArray([]);
Array.isArray([1]);
Array.isArray(new Array());
Array.isArray(new Array('a', 'b', 'c', 'd'));
Array.isArray(new Array(3));
// Array.prototype은 스스로도 배열입니다
Array.isArray(Array.prototype);

// 모두 false 반환
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });

Array.join()
배열의 모든 요소를 연결해 하나의 문자열로 만듭니다.
반환 값 : 요소가 undefind or null or arr.length 가 0 일 경우 빈 문자열로 변환 합니다.

arr.join(\[separator\])
const elements = ['Fire', 'Air', 'Water'];

console.log(elements.join());
// Expected output: "Fire,Air,Water"

console.log(elements.join(''));
// Expected output: "FireAirWater"

console.log(elements.join('-'));
// Expected output: "Fire-Air-Water"

var a = ['바람', '비', '불'];
var myVar1 = a.join();      // myVar1에 '바람,비,불'을 대입
var myVar2 = a.join(', ');  // myVar2에 '바람, 비, 불'을 대입
var myVar3 = a.join(' + '); // myVar3에 '바람 + 비 + 불'을 대입
var myVar4 = a.join('');    // myVar4에 '바람비불'을 대입

Array.keys()
배열의 각 인덱스를 키 값으로 가지는 새로운 Array Iterator 객체를 반환합니다.

const array1 = ['a', 'b', 'c'];
const iterator = array1.keys();

for (const key of iterator) {
  console.log(key);
}

// Expected output: 0
// Expected output: 1
// Expected output: 2

var arr = ['a', , 'c'];
var sparseKeys = Object.keys(arr);
var denseKeys = [...arr.keys()];
console.log(sparseKeys); // ['0', '2']
console.log(denseKeys);  // [0, 1, 2]

Array.map()
배열 내 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환합니다.

arr.map(callback(currentValue\[, index\[, array\]\])\[, thisArg\])

currentValue : 현재 처리중인 요소
index? : 처리중인 요소의 인덱스
array? : map을 호출한 arr
반환값 : 새로운 Array

const array1 = [1, 4, 9, 16];

// Pass a function to map
const map1 = array1.map(x => x * 2);

console.log(map1);
// Expected output: Array [2, 8, 18, 32]

Array.of()
배열이 아닌 값을 배열로 반환 합니다.
Array 생성자와 차이점이 있습니다.

Array.of(7);       // [7]
Array.of(1, 2, 3); // [1, 2, 3]

Array(7);          // [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]

Array.of(1);         // [1]
Array.of(1, 2, 3);   // [1, 2, 3]
Array.of(undefined); // [undefined]

Array.shift()
원본 배열의 첫번째 요소를 제거하고 반환 합니다.

onst array1 = [1, 2, 3];

const firstElement = array1.shift();

console.log(array1);
// Expected output: Array [2, 3]

console.log(firstElement);
// Expected output: 1

Array.pop()
배열의 마지막 요소를 추출하여 반환 합니다. ( 원본 배열 마지막 요소 제거 됨 )

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

var popped = myFish.pop();

console.log(myFish); // ['angel', 'clown', 'mandarin' ]

console.log(popped); // 'sturgeon'

Array.push()
배열의 마지막 요소에 값을 추가 합니다.

var sports = ['축구', '야구'];
var total = sports.push('미식축구', '수영');

console.log(sports); // ['축구', '야구', '미식축구', '수영']
console.log(total);  // 4

배열을 추가 하기
concat을 사용하면, 새로운 배열을 반환 하지만, apply를 사용하면 원본 배열의 값을 변환 합니다.

var vegetables = ['설탕당근', '감자'];
var moreVegs = ['셀러리', '홍당무'];

// 첫번째 배열에 두번째 배열을 합친다.
// vegetables.push('셀러리', '홍당무'); 하는 것과 동일하다.
Array.prototype.push.apply(vegetables, moreVegs);

console.log(vegetables); // ['설탕당근', '감자', '셀러리', '홍당무']

Array.reduce() // 중요합니다.! Array.reducerRight()

arr.reduce(callback\[, initialValue\])

callback ( 4가지 인수를 받는다. )
acc : 누산기는 콜백의 반환 값을 누적 합니다. ( 만약 initialValue 가 제공 되었다면 initialValue의 값 입니다.)
cur : 처리할 현재의 요소
옵션, currentIndex : 처리중인 현재 요소의 인덱스
옵션, array : reducer를 호출한 배열

옵션, initialValue : 최초 호출에서 사용할 첫 번째 인수에 제공하는 값
(제공 하지 않으면, reducer를 호출한 배열의 첫 번째 값을 사용합니다.)
첫 번째 값이 제공 됨으로, 가장 첫번째 currentVlaue의 값은 배열의 2번째 값이 됩니다.

reducer는 상당히 많은 기능을 구현할수 있습니다. (map, flat, indexof .... )

acc만 때어 놓고 보면, 모든 값을 순차적으로 내부 함수를 처리하고,
처리된 값을 더하여 acc에 저장한다 라고 생각하면 됩니다.

Array.reducerRight() : 배열의 역순으로 값을 처리합니다.

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

// 0 + 1 + 2 + 3 + 4
const initialValue = 0;
const sumWithInitial = array1.reduce(
  (accumulator, currentValue) => accumulator + currentValue,
  initialValue
);

console.log(sumWithInitial);
// Expected output: 10

Array.reverse()
원본 배열의 순서를 반전 합니다.

const a = [1, 2, 3];
console.log(a); // [1, 2, 3]

a.reverse();
console.log(a); // [3, 2, 1]

Array.slice()


https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

댓글

이름만 적고 남길 수 있어요