js function을 둘러보고 가시와요.

Q kim·2021년 1월 11일
0

JS/TS

목록 보기
1/1

원본/출처: https://itnext.io/15-useful-javascript-examples-of-map-reduce-and-filter-74cbbb5e0a1f

reduce를 제대로 쓰지 못하는 그대에게..

"js function 활용에요. for문을 많이 돌리신다면, 한번 둘러보시고 가시는 것도 좋을 거에요.""

1. Set: 배열에서 중복된 값을 제거하기.

const values = [3, 1, 3, 5, 2, 4, 4, 4];
const uniqueValues = [ ...new Set(values)];

// uniqueValuse is [3, 1, 5, 2, 4];

2. filter: 간단한 검색

filter는 filter()의 인자로 들어가는 function을 통과하는 값에 한해 새로운 배열은 반환합니다.

//case-sensitive
const users = [
  { id: 11, name: 'Adam', age: 23, group: 'editor' },
  { id: 47, name: 'John', age: 28, group: 'admin' },
  { id: 85, name: 'William', age: 34, group: 'editor' },
  { id: 97, name: 'Oliver', age: 28, group: 'admin' }
];

let res = users.filter(it => it.name.includes('Oliver'));
// res is [{id: 97, name: "Oliver", age: 28, group: "admin"}]
//case-insensitive
let res = users.filter(it => new RegExp('oli', "i").test(it.name));

// res is = 
// [
//   { id: 97, name: 'Oliver', age: 28, group: 'admin' }
// ]

3. some: 유저의 권한 확인할 때

some() 메서드는 적어도 한개의 요소가 인자로 들어오는 함수을 통과하는지 하지 않는지를 반환합니다.

const hasAdmin = users.some(user => user.group === 'admin');
// hasAdmin is true

reduce 기본 형태

[0, 1, 2, 3, 4].reduce(function(accumulator, currentValue, currentIndex, array) {
  return accumulator + currentValue;
});

4. reduce: 배열들을 평평하게 만들기.

const nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let flat = nested.reduce((acc, it) => [...acc, ...it]);

// flat is [1, 2, 3, 4, 5, 6, 7, 8, 9]

5. reduce: 빈도수 체크

const users = [
  { id: 11, name: 'Adam', age: 23, group: 'editor' },
  { id: 47, name: 'John', age: 28, group: 'admin' },
  { id: 85, name: 'William', age: 34, group: 'editor' },
  { id: 97, name: 'Oliver', age: 28, group: 'admin' }
];
const groupByAge = users.reduce((acc, it) => {
  acc[it.age] = acc[it.age] + 1 || 1;
  return acc;
}, {});
// groupByAge is {23: 1, 28: 2, 34: 1}

6. reduce: 배열 객체에 key를 만들어줍니다.

const uTable = users.reduce((acc, it) => (acc[it.id] = it, acc), {})
// uTable equals:
{
  11: { id: 11, name: 'Adam', age: 23, group: 'editor' },
  47: { id: 47, name: 'John', age: 28, group: 'admin' },
  85: { id: 85, name: 'William', age: 34, group: 'editor' },
  97: { id: 97, name: 'Oliver', age: 28, group: 'admin' }
}

7. Set & map: 배열 객체내에서 특정 필드의 유니크값들만 뽑아봅시다.

const listOfUserGroups = [ ...new Set(users.map(it => it.group))];

// listOfUserGroups is ['editor', 'admin'];

8. map: 단위가 다른 값들을 기준 값에 맞게 변형합시다.

const celsius = [-15, -5, 0, 10, 16, 20, 24, 32]
const fahrenheit = celsius.map(t => t * 1.8 + 32);

// fahrenheit is [5, 23, 32, 50, 60.8, 68, 75.2, 89.6]

9. filter: 교집합 구하기.

const arrA = [1, 4, 3, 2];
const arrB = [5, 2, 6, 7, 1];

arrA.filter(it => arrB.includes(it)); // returns [1, 2]

10. map: 객체를 query String으로 바꾸기

const params = {lat: 45, lng: 6, alt: 1000};

const queryString = Object.entries(params).map(p => encodeURIComponent(p[0]) + '=' + encodeURIComponent(p[1])).join('&')

// queryString is "lat=45&lng=6&alt=1000"

11. reduce: 키와 값 반전시키기.

const cities = {
  Lyon: 'France',
  Berlin: 'Germany',
  Paris: 'France'
};

let countries = Object.keys(cities).reduce(
  (acc, k) => (acc[cities[k]] = [...(acc[cities[k]] || []), k], acc) , {});
// countries is
// {
//   France: ["Lyon", "Paris"],
//   Germany: ["Berlin"]
// }
profile
https://medium.com/nodejs-server

0개의 댓글