자바스크립트 배열 심화 [2] – find/findIndex 메소드, some/every, flat/flatmap, 정렬

메소드 체이닝

const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];

// The Magic of Chaining Methods
const eurToUsd = 1.1;
console.log(movements);

// PIPELINE
const totalDepositsUSD = movements
  .filter(mov => mov > 0)
  .map((mov, i, arr) => {
    return mov * eurToUsd;
  })
  .reduce((acc, mov) => acc + mov, 0);
  • 여러 메소드를 체이닝해서 코드를 간결하게 표현할 수 있다.
  • splice와 같이 array를 mutate 하는 메소드는 체이닝하지 않는 것이 좋다.

find / findIndex 메소드

// The find Method
const firstWithdrawal = movements.find(mov => mov < 0);
console.log(movements); // [200, 450, -400, 3000, -650, -130, 70, 1300]
console.log(firstWithdrawal); // -400

console.log(accounts); // object가 담긴 array
const account = accounts.find(acc => acc.owner === 'Jessica Davis');
console.log(account); // {owner: 'Jessica Davis', movements: Array(8), interestRate: 1.5, pin: 2222}
  • find: 조건을 만족하는 first element만 리턴한다.
  • 조건은 콜백 함수 형태로 넣어줘야 한다.
  • 객체가 담긴 배열의 프로퍼티를 조건으로 활용할 수 있어서 편리하다.
btnClose.addEventListener('click', function (e) {
  e.preventDefault();

  if (
    inputCloseUsername.value === currentAccount.username &&
    Number(inputClosePin.value) === currentAccount.pin
  ) {
    const index = accounts.findIndex(
      acc => acc.username === currentAccount.username
    );
    console.log(index);
    // .indexOf(23)

    // Delete account
    accounts.splice(index, 1);

    // Hide UI
    containerApp.style.opacity = 0;
  }

  inputCloseUsername.value = inputClosePin.value = '';
});
  • findIndex: 조건에 맞는 요소의 인덱스를 반환한다.

some / every 메소드

// some and every
console.log(movements);

// EQUALITY
console.log(movements.includes(-130)); // true

// SOME: CONDITION
console.log(movements.some(mov => mov === -130)); // true

const anyDeposits = movements.some(mov => mov > 0);
console.log(anyDeposits); // true

// EVERY
console.log(movements.every(mov => mov > 0)); // false
console.log(account4.movements.every(mov => mov > 0)); // true

// Separate callback
const deposit = mov => mov > 0;
console.log(movements.some(deposit)); // true
console.log(movements.every(deposit)); // false
console.log(movements.filter(deposit)); // [200, 450, 3000, 70, 1300]
  • some: 조건에 맞는 요소가 하나라도 있으면 true를 반환한다.
  • every: 요소가 전부 조건에 맞으면 true를 반환한다.

flat / flatMap

// flat and flatMap
const arr = [[1, 2, 3], [4, 5, 6], 7, 8];
console.log(arr.flat()); // [1, 2, 3, 4, 5, 6, 7, 8]

const arrDeep = [[[1, 2], 3], [4, [5, 6]], 7, 8];
console.log(arrDeep.flat(2)); //  [1, 2, 3, 4, 5, 6, 7, 8]

// flat
const overalBalance = accounts
  .map(acc => acc.movements)
  .flat()
  .reduce((acc, mov) => acc + mov, 0);
console.log(overalBalance); // 17840

// flatMap
const overalBalance2 = accounts
  .flatMap(acc => acc.movements)
  .reduce((acc, mov) => acc + mov, 0);
console.log(overalBalance2); // 17840
  • flat: 배열에 담긴 배열들을 flatten 해주는 아주 편리한 기능이다!
  • flatMap: map과 flat을 체이닝한 기능이다.

배열 Sorting

// Sorting Arrays

// Strings
const owners = ['Jonas', 'Zach', 'Adam', 'Martha'];
console.log(owners.sort());
console.log(owners);

// Numbers
console.log(movements);

// return < 0, A, B (keep order)
// return > 0, B, A (switch order)

// Ascending
// movements.sort((a, b) => {
//   if (a > b) return 1;
//   if (a < b) return -1;
// });
movements.sort((a, b) => a - b);
console.log(movements);

// Descending
// movements.sort((a, b) => {
//   if (a > b) return -1;
//   if (a < b) return 1;
// });
movements.sort((a, b) => b - a);
console.log(movements);
  • 콜백 함수를 인자로 넣을 수 있으므로 소팅 기준을 복잡하게 지정하는 것도 가능하다.

배열을 만들고 채우는 다양한 방법

// More Ways of Creating and Filling Arrays
const arr = [1, 2, 3, 4, 5, 6, 7];
console.log(new Array(1, 2, 3, 4, 5, 6, 7)); // [1, 2, 3, 4, 5, 6, 7]

// Emprty arrays + fill method
const x = new Array(7);
console.log(x); // [empty × 7]
// console.log(x.map(() => 5));
x.fill(1, 3, 5);
x.fill(1);
console.log(x); //  [1, 1, 1, 1, 1, 1, 1]

arr.fill(23, 2, 6);
console.log(arr); // [1, 2, 23, 23, 23, 23, 7]

// Array.from
const y = Array.from({ length: 7 }, () => 1);
console.log(y); // [1, 1, 1, 1, 1, 1, 1]

const z = Array.from({ length: 7 }, (_, i) => i + 1);
console.log(z); // [1, 2, 3, 4, 5, 6, 7]

labelBalance.addEventListener('click', function () {
  const movementsUI = Array.from(
    document.querySelectorAll('.movements__value'),
    el => Number(el.textContent.replace('€', ''))
  );
  console.log(movementsUI);

  const movementsUI2 = [...document.querySelectorAll('.movements__value')];
});
  • fill: arr.fill(value, start, end)
  • from: arr.from(이터러블, 매핑할 함수)

Leave a Reply

Your email address will not be published. Required fields are marked *