[알고리즘] ES6로 활용하기


1. 구조 분해 할당

  • 배열 또는 객체 요소 분해

배열 구조 분해 할당

const arr = ["Hello", "World", "!"];
const [first, second] = arr;
console.log(first, second);

객체 구조 분해 할당

const obj = { name: "Dongnyeong", age: 29 };
const { name, age } = obj;
console.log(name, age);
//요소 삭제
const obj = { name: "Dongnyeong" };
obj.age = 29;
delete obj.age;
console.log(obj); // { name: 'Dongnyeong' }

값 교환하기

  1. swap 로직
let a = 5;
let b = 10;
let temp;

temp = a;
a = b;
b = temp;
console.log(a, b); // 10, 5
  1. 구조 분해 할당 swap 로직
let a = 5;
let b = 10;
[a, b] = [b, a];
console.log(a, b); // 10, 5

2. 비구조화 할당 - 함수에 객체를 인수로 전달할 때 필요한 것만 꺼내서 사용할 수 있는 문법

const makePerson = ({ familyName, givenName, address }) => {
  return {
    name: `${familyName} ${givenName}`,
    address,
  };
};

const person = makePerson({
  familyName: "Kim",
  givenName: "Dongnyeong",
  address: "Seoul",
  country: "Korea",
});

console.log(person); // { name: 'Kim Dongnyeong', address: 'Seoul' }

3. 스프레드 연산 - 배열 또는 객체를 여러개로 합칠 때

// 배열 병합
const evenNumbers = [2, 4, 6, 8, 10];
const oddNumbers = [1, 3, 5, 7, 9];
const numbers = [...evenNumbers, ...oddNumbers];
console.log(numbers); //  [2, 4, 6, 8, 10, 1, 3, 5, 7, 9]
//객체 병합 - 키가 같은 객체를 병합하면 스프레드 연산을 사용한 객체로 덮음
const person = {
  familyName: "Kim",
  givenName: "Dongnyeong",
  address: "Seoul",
  country: "Korea",
};

const address = {
  country: "USA",
  city: "New York",
};

const merge = { ...person, ...address };
console.log(merge); // {familyName: "Kim", givenName: "Dongnyeong", address: "USA", country: "USA", city: "New York"}
// 배열 내 같은 요소 제거
const names = ["Kim", "Lee", "Kim", "Park", "Lee"];
const uniqueNames = [...new Set(names)];
console.log(uniqueNames); // ["Kim", "Lee", "Park"]