[JS] map, filter, reduce method

Hyodduru ·2021년 12월 17일
0

JavaScript

목록 보기
41/60
post-thumbnail

강의 출처 : The Complete JavaScript Course 2022 Jonas (Udemy)

Creating DOM Elements

insertAdjacentHTML

insertAdjacentHTML() method는 이미 사용 중인 element를 다시 parsing 하지 않아서 'innerHtml'보다 작업이 덜 드므로 빠르다.

element.insertAdjacentHTML(position, text);

Position Option

  • 'beforebegin': Before the element itself.
  • 'afterbegin': Just inside the element, before its first child.
  • 'beforeend': Just inside the element, after its last child.
  • 'afterend': After the element itself.

ex)

const calcdisplayMovements = function (movements) {
  containerMovements.innerHTML = '';

  movements.forEach(function (mov, i) {
    const type = mov > 0 ? 'deposit' : 'withdrawal';
    const html = `
    <div class="movements__row">
      <div class="movements__type movements__type--deposit">${i + 1} 
        ${type}</div>
      <div class="movements__value">${mov}€</div>
    </div>`;
    containerMovements.insertAdjacentHTML('afterBegin', html);
  });
};
calcdisplayMovements(account1.movements);

참고)
textContext와 innerHTML의 차이 :

  • textContext : text 그 자체를 return한다.
  • innerHTML : HTML의 모든 요소를 return한다. ex) tag

Data Transformations : map, filter, reduce

map

map returns a new array containing the result of applying an operation on all original array elements

filter

filter returns a new array containing the array elements that passed a specified test codition

reduce

reduce boils(reduce) all array elements down to one single value. ex) adding all element together

The map Method

기존의 array 바꾸지 않음. 새로운 array를 return.

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

const movementsUSD = movements.map(mov => mov * eurToUsd);

console.log(movements);
console.log(movementsUSD);

const movementsUSDfor = [];
for (const mov of movements) movementsUSDfor.push(mov * eurToUsd);
console.log(movementsUSDfor);

const movementsDescriptions = movements.map(
  (mov, i) =>
    `Movement ${i + 1}: You ${mov > 0 ? 'deposited' : 'withdraw'} ${Math.abs(
      mov
    )}`
);

console.log(movementsDescriptions);
//['Movement 1: You deposited 200', 'Movement 2: You deposited 450', 'Movement 3: You withdraw 400', 
//'Movement 4: You deposited 3000', 'Movement 5: You withdraw 650', 'Movement 6: You withdraw 130', 
//'Movement 7: You deposited 70', 'Movement 8: You deposited 1300']

filter method

const deposits = movements.filter(function (mov) {
  return mov > 0;
});
console.log(movements); //[200, 450, -400, 3000, -650, -130, 70, 1300]
console.log(deposits); //[200, 450, 3000, 70, 1300]

const depositsFor = [];
for (const mov of movements) if (mov > 0) depositsFor.push(mov);
console.log(depositsFor); // [200, 450, 3000, 70, 1300]

const withdrawals = movements.filter(mov => mov < 0);
console.log(withdrawals); //) [-400, -650, -130]

reduce method

array를 return하는 것이 아니라 하나의 value를 return한다는 점 기억할 것!

acc = accumulator -> Snowball

const balance = movements.reduce((acc, cur) => acc + cur, 0);
console.log(balance); //3840

let balance2 = 0;
for (const mov of movements) balance2 += mov;
console.log(balance2); //3840

//Maximum value
const max = movements.reduce((acc, curr) => {
  return acc > curr ? acc : curr;
}, movements[0]);

console.log(max); //3000

The Magic of Chaining Methods

const eurToUsd = 1.1;
const totalDepositUSD = movements
  .filter(mov => mov > 0)
  .map(mov => mov * eurToUsd)
  .reduce((acc, mov) => acc + mov, 0);
console.log(totalDepositUSD); //5522.000000000001

주의 사항)

  • chaining 너무 자주하면 좋지 않음! 과하게 사용하지 말 것.
  • 기존의 array를 바꾸는 splice나 reverse와 같은 함수를 chaining에 사용하지 말 것
profile
꾸준히 성장하기🦋 https://hyodduru.tistory.com/ 로 블로그 옮겼습니다

0개의 댓글