본문 바로가기
JavaScript

[JavaScript] Arrays - 02(forEach, map, filter, reduce, find, findIndex)

by 박헹구 2022. 3. 31.
반응형

 

Arrays

 

 

forEach()

forEach 메서드가 하는 일은 배열을 반복하는 것.

각 반복에서 실행된다. 

forEach 와 for...of 의 차이점

 

forEach에서는 countiue와 break가 전혀 작동하지 않는다. 

forEach는 항상 전체 배열을 반복함. 

 

만약 중간에 멈춰야 하는경우는 for...of를 사용해야 한다. 

 

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

for (const movement of movements) {
  if (movement > 0) {
    console.log(`You deposited ${movement}`);
  } else {
    console.log(`You withdrew ${Math.abs(movement)}`);
  }
}

or

movements.forEach(function (movement) {
  if (movement > 0) {
    console.log(`You deposited ${movement}`);
  } else {
    console.log(`You withdrew ${Math.abs(movement)}`);
  }
});

//result
You deposited 200
You deposited 450
You withdrew 400
You deposited 3000
You withdrew 650
You withdrew 130
You deposited 70
You deposited 1300
const movements = [200, 450, -400, 3000, -650, -130, 70, 1300];

// for (const movement of movements) {
for (const [i, movement] of movements.entries()) {
  if (movement > 0) {
    console.log(`Movement ${i + 1}: You deposited ${movement}`);
  } else {
    console.log(`Movement ${i + 1}: You withdrew ${Math.abs(movement)}`);
  }
}

//forEach
movements.forEach(function (mov, index, array) {
  if (mov > 0) {
    console.log(`Movement ${index + 1}: You deposited ${mov}`);
  } else {
    console.log(`Movement ${index + 1}: You withdrew ${Math.abs(mov)}`);
  }
});


//result
Movement 1: You deposited 200
script.js:89 Movement 2: You deposited 450
script.js:91 Movement 3: You withdrew 400
script.js:89 Movement 4: You deposited 3000
script.js:91 Movement 5: You withdrew 650
script.js:91 Movement 6: You withdrew 130
script.js:89 Movement 7: You deposited 70
script.js:89 Movement 8: You deposited 1300

forEach와 함께 map과 set을 쓰는 경우

const currencies = new Map([
  ['USD', 'United States dollar'],
  ['EUR', 'Euro'],
  ['GBP', 'Pound sterling'],
]);

currencies.forEach(function (value, key, map) {
  console.log(`${key}: ${value}`); 
  //result
//USD: United States dollar
//EUR: Euro
//GBP: Pound sterling
});

//Set
const currenciesUnique = new Set(['USD', 'GBP', 'USD', 'EUR', 'EUR']);
console.log(currenciesUnique);
currenciesUnique.forEach(function (value, _, map) {
  console.log(`${value}: ${value}`);
  //result
//USD: USD
//GBP: GBP
//EUR: EUR
});

Map

배열을 반복한다. 

새 배열을 만든 후에 추가

맵 메서드는 새로운 배열을 내가 작업했던 결과를 포함하여 반환한다. 

 

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

const eurToUsd = 1.1;

// const movementsUSD = movements.map(function (mov) {
//   return mov * eurToUsd;
// });

//arrow function 사용
1️⃣
//const movementsUSD = movements.map(mov => {
//  return mov * eurToUsd;
//});

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

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

or

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

 

1️⃣2️⃣ 결과값

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

 for (const movement of movements) {
 for (const [i, movement] of movements.entries()) {
   if (movement > 0) {
    console.log(`Movement ${i + 1}: You deposited ${movement}`);
   } else {
     console.log(`Movement ${i + 1}: You withdrew ${Math.abs(movement)}`);
  }
 }
 
 or

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


filter

어떠한 조건을 정하고 테스트를 통과(필터링)된 배열로 새로 반환된다. 

 

 

 

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

// 1️⃣
const deposits = movements.filter(function (mov) {
  return mov > 0;
});

or

// 2️⃣
const depositsFor = [];
for (const mov of movements) if (mov > 0) depositsFor.push(mov);

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

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

reduce

reduce는 모든 배열 요소를 하나의 단일 값으로 축소한다. 

예를 들어 배열의 모든수의 합을 구할 때 같은 경우.  새 배열이 없다.  리듀스 결과만 있을 뿐이다. 

 

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

//accumulator => SnowBall
const balance = movements.reduce(function (acc, cur, i, arr) {
  return acc + cur;
}, 0);

console.log(balance); //3840

///////// arrow function으로 변경했을 경우

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


//for..of로 했을 경우
let balance2 = 0;

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

계산의 과정을 확실하게 보기 위해서는 

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

//accumulator => SnowBall
const balance = movements.reduce(function (acc, cur, i, arr) {
  console.log(`Iteration ${i}: ${acc}`);
  return acc + cur;
}, 0);

console.log(balance);

//최대값 찾기
const max = movements.reduce((acc, mov) => {
  if (acc > mov) return acc;
  else return mov;
}, movements[0]);

console.log(max); // 3000

 


find()

 

filter메서드와 비슷하지만 filter는 조건에 일치하는 모든 요소를 반환하지만 find 메서드는 첫번재와 두번째만 반환한다. 또한 find메서드는 새배열이 아닌 요소 자체만 반환한다. 

일반적으로 Find메서드의 목표는 정확히 하나의 요소를 찾는 것이다. 

const account1 = {
  owner: 'Jonas Schmedtmann',
  movements: [200, 450, -400, 3000, -650, -130, 70, 1300],
  interestRate: 1.2, // %
  pin: 1111,
};

const account2 = {
  owner: 'Jessica Davis',
  movements: [5000, 3400, -150, -790, -3210, -1000, 8500, -30],
  interestRate: 1.5,
  pin: 2222,
};

const account3 = {
  owner: 'Steven Thomas Williams',
  movements: [200, -200, 340, -300, -20, 50, 400, -460],
  interestRate: 0.7,
  pin: 3333,
};

const account4 = {
  owner: 'Sarah Smith',
  movements: [430, 1000, 700, 50, 90],
  interestRate: 1,
  pin: 4444,
};

const accounts = [account1, account2, account3, account4];

const account = accounts.find(acc => acc.owner === 'Jessica Davis');

console.log(account);

 


findIndex()

요소 자체가 아닌 발견된 요소의 인덱스를 반환한다. 

findIndex() 메서드는 주어진 판별 함수를 만족하는 배열의 첫 번째 요소에 대한 인덱스를 반환합니다. 만족하는 요소가 없으면 -1을 반환합니다.

 

const array1 = [5, 12, 8, 130, 44];

const isLargeNumber = (element) => element > 13;

console.log(array1.findIndex(isLargeNumber));
// expected output: 3

 

 

반응형

댓글