[자바스크립트] 사용도 높은 함수(★)

bunny.log·2023년 3월 28일
0

fill

arr.fill(value[, start[, end]])
  • value
    배열을 채울 값.

  • start Optional
    시작 인덱스, 기본 값은 0.

  • end Optional
    끝 인덱스, 기본 값은 this.length.

  • 반환 값
    변형한 배열.

const arr = new Array(5).fill(5);
console.log(arr) //[5,5,5,5,5]

#기존 배열에 추가하여 생성하기
var answer = [];
answer.push(...Array(6).fill(3));
console.log(answer) //[3,3,3,3,3,3]

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]

from

Array.from(초기화할 배열, 함수 로직 (배열의값, 배열의 인덱스))

const arr = Array.from(Array(5), (function(v,k){
	return k + 1;
}))

console.log(arr) //[1,2,3,4,5]

5x5 행렬만들어 false로 초기화 하기

const graph = Array.from(Array(5), () => {
	Array(5).fill(false);
})

nxn 행렬만들어 0로 초기화 하기

const array = new Array(n).fill(0);
const result = Array.from({ length: n }, () => array);

bomb
[[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ],
[ 0, 0, 0, 0, 0 ]]

const bomb = Array.from({ length: board.length }, () => Array(board.length).fill(0));

Join

배열 값을 ","를 추가하여 문자열로 합치기

const arr = [1,2,3,4,5];
console.log(arr.join(",")); //1,2,3,4,5

concat

배열 합치기

const arr = [1,2,3,4,5];
const arr2 = [6,7,8,9,10];
console.log(arr.concat(arr2)); //[1,2,3,4,5,6,7,8,9,10]

slice

slice() 메서드는 어떤 배열의 begin 부터 end 까지(end 미포함)에 대한 얕은 복사본을 새로운 배열 객체로 반환합니다. 원본 배열은 바뀌지 않습니다.

slice(복사할 배열의 값 첫번째 index, 복사할 배열 값의 마지막 인덱스 + 1);
[주의] 마지막 인덱스앞 값까지 복사된다.

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

console.log(animals.slice(2));
// Expected output: Array ["camel", "duck", "elephant"]

console.log(animals.slice(2, 4));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice(1, 5));
// Expected output: Array ["bison", "camel", "duck", "elephant"]

console.log(animals.slice(-2));
// Expected output: Array ["duck", "elephant"]

console.log(animals.slice(2, -1));
// Expected output: Array ["camel", "duck"]

console.log(animals.slice());
// Expected output: Array ["ant", "bison", "camel", "duck", "elephant"]

splice

원본 배열을 변화시켜 배열 요소 삭제하기

splice(복사할 배열의 값 첫번째 index, 복사할 배열의 값 첫번째 index 부터 삭제할 요소의 개수);
[주의] 마지막 인덱스앞 값까지 복사된다.

const arr = [1,2,3,4,5,6];
console.log(arr.slice(2,2))  // [1,2,5,6]

원본 배열안에서 [3,4] 값이 삭제 되었다.

예제 1) 배열 요소 추가하기

var mine = [0,1,2,3];

// 배열 2번째 위치한곳에 숫자 5를 추가한다.
mine.splice(2,0,5); // [0, 1, 5, 2, 3]

// 배열 2번째 위치한곳에 숫자 5,7을 추가한다.
mine.splice(2,0,5,7); //[0, 1, 5, 7, 2, 3]

예제 2) 배열 요소 제거하기

var mine = [0,1,2,3];

// 배열 1번째 부터 1개를 제거한다.
mine.splice(1,1); // [0, 2, 3]

// 배열 1번째 부터 2개를 제거한다.
mine.splice(1,2); //[0, 3]

예제 3) 배열 요소 교체하기

var mine = [0,1,2,3];

// 배열 1번째부터 1개를 제거하고 숫자 5로 추가한다.
mine.splice(1,1,5); // [0, 5, 2, 3]

// 배열 1번째부터 2개를 제거하고 숫자 5로 추가한다.
mine.splice(1,2,5); //[0, 5, 3]

예제 4) 배열 요소 추출하기

var mine = [0,1,2,3];

// 배열 1번째 부터 1개를 제거한다.
var remove = mine.splice(1,1); // [1]

// 배열 1번째 부터 2개를 제거한다.
var remove = mine.splice(1,2); //[1, 2]

splice() 배열 요소 제거, 추가

splice() 메서드로 요소를 삭제하는 동시에 바로 새 요소를 추가할 수도 있습니다. deleteCount 매개변수 뒤에 배열에 추가할 요소를 전달하기만 하면 됩니다.

필수 매개변수와 선택적 매개변수를 모두 전달하는 경우의 문법은 다음과 같습니다.

// 필수 매개변수와 선택적 매개변수가 포함된 splice() 문법 
Array.splice(start, deleteCount, newItem, newItem, newItem, ...)

다음 예시에서는 months 배열에 "March"와 "April"을 추가하면서 "Monday"와 "Tuesday"를 제거하는 방법을 보여줍니다.

let months = ["January", "February", "Monday", "Tuesday"];
let days = months.splice(2, 2, "March", "April"); // 요소 두 개를 제외하고, 다른 요소를 추가

console.log(days); // ["Monday", "Tuesday"]
console.log(months); // ["January", "February", "March", "April"]

splice() 배열의 중간에 값 추가, 삭제하기

array.splice(start[, deleteCount[, item1[, item2[, ...]]]])

splice() 함수는 start index부터 deleteCount만큼의 원소를 삭제하고, 뒤 이어 오는 items를 start index 위치에 추가합니다.

startdeleteCountitems리턴값
변경을 시작할 배열의 시작 indexstart index부터 deleteCount 갯수만큼 원소를 삭제합니다.deleteCount가 입력되지 않으면, start index 이후의 모든 값이 삭제됩니다.배열의 start index에 item들을 추가합니다.삭제된 원소(element)의 배열을 리턴합니다.

for of

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

for(const item of arr){
	console.log(item)
}

console.log(item); // 1,2,3,4,5

delete 객체 값 삭제

delete 사용

const object = { name:'bunny', email:'bunny@korea.com', phone:'010-000-0000}

delete object.name;
console.log(object); //{ email:'bunny@korea.com', phone:'010-000-0000}

in 객체 값이 존재

in 사용

const object = { name:'bunny', email:'bunny@korea.com', phone:'010-000-0000}

console.log('name' in object); //true
console.log('sex' in object); //false

오브젝트의 key 집합과 value값 알아내는 방법

  • Object.keys 사용하면 key 값 배열을 얻을 수 있다.
  • Object.values 사용하면 value 값 배열을 얻을 수 있다.
const obj = { name:'bunny', email:'bunny@korea.com', phone:'010-000-0000}

console.log(Object.keys(obj)) // [name, email, phone]
console.log(Object.keys(obj)) // [bunny, bunny@korea.com, 010-000-0000]

객체 순회 for in

const obj = { name:'bunny', email:'bunny@korea.com', phone:'010-000-0000}
for(const key in obj){
	console.log(key, obj[key]); 
    // name  bunny 
	// email bunny@korea.com
    // phone 010-000-0000
}

객체를 배열로 변환하기 Object.entries

순서로 주어진 객체 자체의 enumerable 속성 [key, value] 쌍의 배열을 반환합니다.

const productList = {
  backpack: 1200,
  pencil: 800,
  eraser: 600,
}

const productArray = Object.entries(productList);
// [ [ 'backpack', 1200 ], [ 'pencil', 800 ], [ 'eraser', 600 ] ]

배열을 객체로 변환하기 Object.fromEntries

반대로 배열을 객체로 변환하는 것도 가능합니다.
Object.fromEntries(대상 배열명)은 [["키 1", "값 1"], ["키 2", "값 2"] ... ] 형태의 배열을 객체로 변환해 리턴합니다.

const productArray = [
  ['backpack', 1200],
  ['pencil', 800],
  ['eraser', 600],
]

Object.fromEntries(productArray) // { backpack: 1200, pencil: 800, eraser: 600 }

이를 사용해, 객체의 각 요소에 배열에 메서드를 적용해 간단하게 값을 조작하는 것이 가능합니다.

  • 배열의 map 메서드를 사용해 각 키의 값을 2배 증가시키는 예시
const productList = {
  backpack: 1200,
  pencil: 800,
  eraser: 600,
}

Object.fromEntries(Object.entries(productList).map(([key, price]) => [key, price * 2]))
// { backpack: 2400, pencil: 1600, eraser: 1200 }

flat()

flat은 위 처럼 하위 배열을 합칠때 사용합니다. 사용법은 매우 간단합니다.

const exampleArray = ["a", ["b"], ["c"]];
const newArray = exampleArray.flat();
//newArray = ['a','b','c'];
 

빈 요소가 있으면 무시됩니다.

const exampleArray = ["a", , ["b"], ["c"]];
const newArray = exampleArray.flat();
//newArray = ['a','b','c'];

depth에 따라 합치는 정도를 나눌 수 있습니다.

const exampleArray = ["a", ["b", ["c"]]];
const newArray = exampleArray.flat();
//newArray = ['a','b',['c']];

const flat1 = exampleArray.flat(1);
//newArray = ['a','b',['c']];

const flat2 = exampleArray.flat(2);
//newArray = ['a','b','c'];

flatMap()

flatMap 메소드는 flat과 map을 합친 메소드입니다. map대신 flatMap을 사용하시면 됩니다.
위처럼 하위배열을 결합하는데 조건에 따라 결합을 할때 사용하시면 됩니다.

const alphabets = ['a', 'b', 'c'];
const fruits = ['apple', 'banana', 'cherry'];

const mappedWord = alphabets.map((alphabet, index) => [alphabet, fruits[index]]);
console.log(mappedWord)
// [ [ 'a', 'apple' ], [ 'b', 'banana' ], [ 'c', 'cherry' ] ]
// 즉 Array안의 요소를 map 의 콜백함수의 return 값으로 채운다.


const flatMappedWord = alphabets.flatMap((alphabet, index) => [alphabet, fruits[index]]);
console.log(flatMappedWord)
// [ 'a', 'apple', 'b', 'banana', 'c', 'cherry' ]
// map 과의 차이점은 map 에서 한개의 깊이를  평평하게 만들어 주는 것이다.

const flatMappedWordTwo = alphabets.flatMap((alphabet, index) => [[alphabet, fruits[index]]]);
console.log(flatMappedWordTwo)
// [ [ 'a', 'apple' ], [ 'b', 'banana' ], [ 'c', 'cherry' ] ]
// 즉 return 값을 2차원 배열로 전달 받게 되면 1차원 배열로 변경하는 것이다.

1차원 배열일 경우 map 은 생성된 배열이 2차원 배열이지만 flatMap의 경우 1단계 flat되어 1차원 배열이 생성된 것을 볼 수 있다.
그렇기 때문에 2차원 배열을 return 받았을 경우에는 flatMap 으로 생성된 배열은 2차원 배열이 될 것이다.

every

every 함수는 배열의 모든 요소가 callbackFunction 에서 true를 리턴해야 true를 리턴, 하나라도 false가 떨어지면 false를 리턴합니다.

array.every(callbackFunction(currentValue, index, array), thisArg)

some

some 함수는 배열의 요소 중 하나라도 callbackFunction에서 true를 리턴하면 true를 리턴 합니다.

array.some(callbackFunction(currentValue, index, array), thisArg)

includes

var a = [1,2,3,4,5,1,2,3]

a.includes(3)
//true

a.includes(6)
//false

find

콜백함수의 조건에 만족하는 첫번째 배열요소를 반환한다.
만약 조건에 만족하는 요소가 없다면, undefined를 리턴한다.

[특징]

  1. 배열을 순환하면서 조건에 맞는 요소를 찾는 순간, 순환을 멈추고 즉시 값을 반환한다.
  2. 특정 index 에 값이 없거나, delete 됬어도 콜백함수 조건에 맞는지 확인한다.
  3. find() 자체는 원본배열을 변형시키지 않는다(callback함수에서 변형시킬수는 있어도)
  4. find() 첫 호출 당시 값이 존재했고, 콜백함수 처리 중에 값이 변경된 경우, 변경된 값으로 검사한다. (앞의 index에서 실행된 콜백함수가 이후 index의 값을 변경시킨 경우)

[주의]

  • 어떤 값의 index 를 찾고싶은 경우, indexOf() 를 사용하는게 낫다.
  • 어떤 값의 존재유무를 알고싶은 경우, includes() 를 사용하는게 낫다.
  • 콜백함수 조건에 맞는 요소가 있는지/없는지 알고싶은 경우, some() 을 사용하는게 낫다.
var friends = [
    {name: 'Son', age: 30},
    {name: 'Kane', age: 29},
    {name: 'Lucas', age: 30}
];


var result = friends.find( ({ name }) => name == 'Kane');

findIndex

findIndex(testFn(element[, index[, array]])[, thisArg])

1) 간단한 배열 예제와 함께 배열 findIndex() 메서드 사용

let ranks = [1, 5, 7, 8, 10, 7];
let index = ranks.findIndex(rank => rank === 7);
console.log(index);
//2

조건을 일치하는 배열 요소가 없는 경우 -1을 반환합니다.

2) 보다 복잡한 조건에서 Array findIndex() 메서드 사용

let ranks = [1, 5, 7, 8, 10, 7];

let index = ranks.findIndex(
    (rank, index) => rank === 7 && index > 2
);

console.log(index);

3) 객체 배열과 함께 Array findIndex() 메서드 사용
다음 예제에서는 Array findIndex() 메서드를 사용하여 가격이 1000보다 큰 첫 번째 제품의 인덱스를 찾습니다.

const products = [
  { name: 'Phone', price: 999 },
  { name: 'Computer', price: 1999 },
  { name: 'Tablet', price: 995 },
];

const index = products.findIndex(product => product.price > 1000);

console.log(index); // 1

new Map()

 #객체 생성
 var hash = new Map();

 #값 가져오기
 hash.get(key);
 
 #값 넣기
 hash.set(key, value);
 
 #값 삭제
 hash.delete(key);
 
 #key의 존재여부 boolean으로 반환
 map.has(key);
 
 #맵 안의 모든 요소 제거
 map.clear();
 
 #요소의 개수 반환
 map.size

forEach()로 Map의 key-value 요소를 순회
★★★ forEach 구문을 사용할 때에는 key와 value의 순서가 반대라는 것만 기억하면 되겠다.

let myMap = new Map([
  ['c', 2],
  ['a', 4],
  ['d', 1],
  ['b', 3],
]);

myMap.forEach((value, key) => {
  console.log("key: " + key + ", value: " + value);
});

for...of 로 Map의 모든 요소 순회

let myMap = new Map([
  ['c', 2],
  ['a', 4],
  ['d', 1],
  ['b', 3],
]);

for (const [key, value] of myMap) {
  console.log("key: " + key + ", value: " + value);
}

keys(), values()로 Map의 모든 요소 순회

let myMap = new Map([
  ['c', 2],
  ['a', 4],
  ['d', 1],
  ['b', 3],
]);

console.log("keys:");
for (const key of myMap.keys()) {
  console.log(key);
}

console.log("values:");
for (const value of myMap.values()) {
  console.log(value);
}

new Map() sort 하기

const mapToArray = [...arrayToMap];
const mapToArray_2 = Array.from(arrayToMap);

mapToArray.sort((a, b) => b[1] - a[1]); // value값 기준 내림차순정렬

mapToArray.sort((a, b) => b[0] - a[0]); // key값 기준 내림차순정렬

mapToArray.sort((a, b) => a[1] - b[1]); // value값 기준 오름차순정렬

mapToArray.sort((a, b) => a[0] - b[0]); // key값 기준 오름차순정렬

필요에 의해 다시 Map으로 변환시켜도 된다.

const sortedMap = new Map(mapToArray.sort((a, b) => b[1] - a[1]));

배열을 map을 이용하여 new Map으로 변환하기

const animals = [
    { name: 'doggo', age: 0 },
    { name: 'catch', age: 3 },
    { name: 'birdy', age: 1 },
];

const map = new Map(animals.map(animal => [animal.name, animal.age]));

배열을 reduce 이용하여 new Map으로 변환하기

const array = [
    {key: 'a', value: '1'},
    {key: 'b', value: '2'}
]
const arrMap = array.reduce((map, obj) => {
    map.set(obj.key, obj.value);
    return map;
}, new Map);

new Set()

세트(set)는 한마디로 순서가 없는 중복되지 않은 데이터의 집합

  1. 세트는 데이터를 순서없이 저장합니다. 따라서 배열처럼 인덱스를 통해서 접근할 수가 없습니다.
  2. 세트는 중복된 데이터를 허용하지 않습니다.
const numSet = new Set([1, 2, 3]); // Set(3) {1, 2, 3}

add() 값 추가

set.add(1); // Set(1) {1}
set.add("A"); // Set(2) {1, 'A'}
set.add(true); // Set(3) {1, 'A', true
set.add(1).add("A").add(true); // Set(3) {1, 'A', true}

delete() 값 추가
Set의 delete() 메서드를 사용하면 세트로 부터 특정 값을 삭제할 수 있는데요. delete() 메서드에 인자로 넘기는 값이 세트에 존재하여 성공적으로 삭제하였다면 true를 반환하고, 해당 값이 세트에 존재하지 않아서 삭제에 실패하였다면 false를 반환합니다.

set.delete(1); // true
set.delete(2); // false

has() 값 존재 여부 확인

if (set.has("A")) {
  console.log("A는 세트에 존재합니다."); // A는 세트에 존재합니다.
}
const result = set.has("B") ? "YES" : "NO"; // NO

값의 개수 확인
세트의 size 속성을 통해서 해당 세트의 길이, 즉 얼마나 많은 값이 저장되어 있는지를 알아낼 수 있습니다.

set.size

모든 값 제거
Set 객체의 모든 값을 제거하려면 clear() 메서드를 사용합니다.

set.clear()

세트 순회
세트에 저장되어 있는 모든 값을 순회하고 싶을 때는 어떻게 해야 할까요? 이 때는 for 루프문 안에서 of 연산자를 사용하면 됩니다.

for (const num of numSet) {
  console.log(num);
}

numSet.forEach((num) => console.log(num));

sort() - 2차원 배열 정렬

정렬 방식은 동일, 정렬 기준으로 삼고자 하는 배열 요소(인덱스로 구분)를 기준으로 비교 함수 작성해야함!

const arr5 = [
  [10, 2],
  [7, 8],
  [3, 3],
  [-1, 3],
  [99, 99],
  [-10, 10],
];

arr5.sort((prev, cur) => {
  // 2번째 배열 요소를 기준으로 오름차순
  if (prev[1] > cur[1]) return 1;
  if (prev[1] < cur[1]) return -1;
});
console.log(arr5); //[ [ 10, 2 ], [ 3, 3 ], [ -1, 3 ], [ 7, 8 ], [ -10, 10 ], [ 99, 99 ] ]


const arr6 = [
  [2, 9, 2],
  [-1, -2, -3],
  [0, 3, 3],
  [12, -1, 6],
  [9, 10, 11],
  [-1, -1, -1],
  [1, 0, -5],
];

arr6.sort((prev, cur) => {
  // 3번째 배열 요소를 기준으로 내림차순
  if (prev[2] < cur[2]) return 1;
  if (prev[2] > cur[2]) return -1;
});

console.log(arr6);
//[[ 9, 10, 11 ],
//  [ 12, -1, 6 ],
//  [ 0, 3, 3 ],
//  [ 2, 9, 2 ],
//  [ -1, -1, -1 ],
//  [ -1, -2, -3 ],
//  [ 1, 0, -5 ]
//]

.
.
.
.
.

참고
findIndex
https://5takoo.tistory.com/222

new Map()
https://codechacha.com/ko/javascript-map-iteration/

new Set()
https://www.daleseo.com/js-set/

profile
더 많은 유익한 내용은 ->> https://github.com/nam-yeun-hwa

0개의 댓글