[JS] find, findIndex, some, every, flat, flatMap, Sort, fill

hoje15v·2021년 12월 20일
0

JavaScript

목록 보기
42/78
post-thumbnail

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

The find Method

new array를 return하는 것이 아니라 조건에 부합하는 첫번째 아이템을 return한다.

const firstWithdrwal = movements.find(mov => mov < 0);

console.log(movements);
console.log(firstWithdrwal); //-400

console.log(accounts);

const account = accounts.find(acc => acc.owner === 'Jessica Davis');
console.log(account); //{owner: 'Jessica Davis', movements: Array(8), interestRate: 1.5, pin: 2222, username: 'jd'}
btnTransfer.addEventListener('click', e => {
  e.preventDefault();
  const amount = Number(inputTransferAmount.value);
  const receiverAcc = accounts.find(
    acc => acc.username === inputTransferTo.value
  );
  inputTransferTo.value = inputTransferAmount.value = '';
  inputTransferAmount.blur();

  if (
    amount > 0 &&
    receiverAcc &&
    currentAccount.balance >= amount &&
    receiverAcc.username !== currentAccount.username
  ) {
    //Doing the transfer
    currentAccount.movements.push(-amount);
    receiverAcc.movements.push(amount);

    //Update UI
    updateUI(currentAccount);
  }
});

The findIndex Method

조건에 부합하는 element의 index 값을 return한다.

btnClose.addEventListener('click', e => {
  e.preventDefault();

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

    //Delete account
    accounts.splice(index, 1);
    //Hide UI
    containerApp.style.opacity = 0;
  }
  inputCloseUsername.value = inputClosePin.value = '';
});

some and every

some Method

불리언 값을 return 한다. 조건에 부합하는 element가 하나라도 있다면 true를 return한다.

//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
btnLoan.addEventListener('click', e => {
  e.preventDefault();

  const amount = Number(inputLoanAmount.value);
  if (amount > 0 && currentAccount.movements.some(mov => mov >= amount * 0.1)) {
    //Add movement
    currentAccount.movements.push(amount);

    //Update UI
    updateUI(currentAccount);

    inputLoanAmount.value = '';
  }
});

every

모든 elements가 조건에 부합할 때만 true를 return한다.

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

// Separate callback
// to not repeat myself
const deposit = mov => mov > 0;
console.log(movements.some(deposit));
console.log(movements.every(deposit));
console.log(movements.filter(deposit));

flat and flatMap

flat Method

nested array와 작업할 때 유용하게 쓸 수 있음.
flat Method는 callback function을 받지 않는다.

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(1)); //[[1, 2], 3, 4, [5, 6], 7, 8] first level까지만 flat하게 만듬.
console.log(arrDeep.flat(2)); // [1, 2, 3, 4, 5, 6, 7, 8]

const accountMovements = accounts.map(acc => acc.movements);
const allMovements = accountMovements.flat();
console.log(allMovements); //[200, 450, -400, 3000, -650, -130, 70, 1300, 5000, 
3400, -150, -790, -3210, -1000, 8500,-30, 200, -200, 340, -300, -20, 50, 400, -460, 
430, 1000, 700, 50, 90]
const overallBalance = allMovements.reduce((acc, mov) => acc + mov, 0);
console.log(overallBalance); //17840

flat chaining

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

// 보통 map을 먼저 사용 => flat

flatMap Method

flat Method와 map Method가 합쳐진 것
map이 받는 callback 함수를 받는다.

const overalBalance2 = accounts
  .flatMap(acc => acc.movements)
  .reduce((acc, mov) => acc + mov, 0);

console.log(overalBalance2); //17840

Sorting Arrays

sort 는 기존의 array를 수정한다.

Sort Method - Strings

const owners = ['Jonas', 'Zach', 'Adam', 'Martha'];
console.log(owners.sort()); // ['Adam', 'Jonas', 'Martha', 'Zach'] A-Z 순서로 배열
console.log(owners); //['Adam', 'Jonas', 'Martha', 'Zach']

Sort Method - Numbers

console.log(movements); //[200, 450, -400, 3000, -650, -130, 70, 1300]
console.log(movements.sort()); //[-130, -400, -650, 1300, 200, 3000, 450, 70]

sort method는 string에 기반하여 분류한다.

Ascending

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

 movements.sort((a, b) => {
   if (a > b) return 1;
   if (b > a) return -1;
 });
movements.sort((a, b) => a - b);
console.log(movements); //[-650, -400, -130, 70, 200, 450, 1300, 3000]

Descending

 movements.sort((a, b) => {
   if (a > b) return -1;
   if (b > a) return 1;
 });
movements.sort((a, b) => b - a);
console.log(movements); //[3000, 1300, 450, 200, 70, -130, -400, -650]

More ways of creating and filling arrays

Empty arrays + fill methods

const x = new Array(7);
console.log(x); // [empty × 7] length가 7인 빈 array가 만들어짐. 
//why? 하나의 인자만 전달할 경우 그 인자 수만큼의 아이템을 가진 empty array를 만들어내는 배열의 특징이 있음.
console.log(x.map(() => 5)); // [empty × 7] 아무 효과 없음.

// x.fill(1);
// console.log(x); //[1, 1, 1, 1, 1, 1, 1] 빈 array를 해당 인자로 채운다.

// x.fill(1, 3, 5); //어느 곳을 정확히 채우고 싶은지 명확히 할 수 있음.
// console.log(x); //[empty × 3, 1, 1, empty × 2]

x.fill(1, 3);
console.log(x); //[empty × 3, 1, 1, 1, 1]

const arr1 = [1, 2, 3, 4, 5, 6, 7];
arr1.fill(23, 4, 6);
console.log(arr1); //[1, 2, 3, 4, 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]

current value 쓰이지 않으므로 첫번째 parameter자리에 _ 적어주기.

참고) querySelecterAll : nodelist를 return한다. something like an array but not REAL array! 그렇게에 map, reduce과 같은 method 가지고 있지 않음.

labelBalance.addEventListener('click', () => {
  const movementsUI = Array.from(
    document.querySelectorAll('.movements__value'),
    el => Number(el.textContent.replace('€', ''))
  );
  console.log(movementsUI); //[1300, 70, -130, -650, 3000, -400, 450, 200]
  //querySelectorAll을 array로 만드는 또다른 방법
  const movementsUI2 = [...document.querySelectorAll('.movements__value')];
  console.log(movementsUI2);
});

Which Array Method to Use?

1) To mutate original array

  • Add to orginal : .push(end), /unshift(start)
  • Remove from original : .pop(end), .shift(start), .splice(any)
  • Others : .reverse, .sort, .fill

2) A new array

  • Computed from original : .map(loop)
  • Filtered using condition : .filter
  • Portion of original : .slice
  • Adding orginal to other : .concat
  • Flattening the original : .flat, .flatMap

3) An array index

  • Based on value : .indexOf
  • Based on test condition : .findIndex

4) An array element

  • Based on test codition : .find

5) Know if array includes

  • Based on value : .includes
  • Based on test condition : .some, .every

6) A new string

  • Based on separator string : .join

7) To transform to value

  • Based on accumulator : .reduce (Boil down array to single value of any type : number, string, boolean, or even new array or object)

8) To just loop array

  • Based on callback : .forEach (Does not create a new array. just loops over it)

Array Methods Practice

const backDepositSum = accounts
  .flatMap(acc => acc.movements)
  .filter(mov => mov > 0)
  .reduce((sum, cur) => sum + cur, 0);

console.log(backDepositSum);
const numDeposits1000 = accounts
   .flatMap(acc => acc.movements)
   .filter(mov => mov >= 1000).length;

const numDeposits1000 = accounts
  .flatMap(acc => acc.movements)
  // .reduce((count, cur) => (cur >= 1000 ? count + 1 : count), 0);
  .reduce((count, cur) => (cur >= 1000 ? ++count : count), 0);

console.log(numDeposits1000); //6

// 참고) count + 1 대신 count++라고 하면 0이 나옴 why?
let a = 10;
console.log(a++); //10 더하더라도 여전히 previous value
console.log(a); //11
console.log(++a); //12
  1. 중요 ~@@@!!
const { deposits, withdrawals } = accounts
  .flatMap(acc => acc.movements)
  .reduce(
    (sums, cur) => {
      // cur > 0 ? (sums.deposits += cur) : (sums.withdrawals += cur);
      sums[cur > 0 ? 'deposits' : 'withdrawals'] += cur;
      return sums;
    },
    { deposits: 0, withdrawals: 0 }
  );
console.log(deposits, withdrawals); //25180 -7340
  1. this is a nice title => This Is a Nice Title
    예외에 해당되는 문자열 들을 배열에 담아두는 것 (ex const exception = [])=> 흔한 패턴임 알아둘 것!
const convertTitleCase = function (title) {
  const capitalize = str => str[0].toUpperCase() + srt.slice(1);
  const exceptions = ['a', 'an', 'the', 'and', 'but', 'or', 'on', 'in', 'with'];
  const titleCase = title
    .toLowerCase()
    .split(' ')
    .map(word => (exceptions.includes(word) ? word : capitalize(word)))
    .join(' ');

  return capitalize(titleCase); // 이렇게 해야 첫문장에 and가 나왔을 때도 And됌!
};
console.log(convertTitleCase('this is a nice Title'));
console.log(convertTitleCase('this is a LONG Title but not too long'));
console.log(convertTitleCase('and here is another title with an EXAMPLE'));
profile
A front web developer & passionate learner loving learning new things and working together with people🦋

0개의 댓글