원본/출처: https://itnext.io/15-useful-javascript-examples-of-map-reduce-and-filter-74cbbb5e0a1f
reduce를 제대로 쓰지 못하는 그대에게..
"js function 활용에요. for문을 많이 돌리신다면, 한번 둘러보시고 가시는 것도 좋을 거에요.""
const values = [3, 1, 3, 5, 2, 4, 4, 4];
const uniqueValues = [ ...new Set(values)];
// uniqueValuse is [3, 1, 5, 2, 4];
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' }
// ]
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;
});
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]
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}
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' }
}
const listOfUserGroups = [ ...new Set(users.map(it => it.group))];
// listOfUserGroups is ['editor', 'admin'];
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]
const arrA = [1, 4, 3, 2];
const arrB = [5, 2, 6, 7, 1];
arrA.filter(it => arrB.includes(it)); // returns [1, 2]
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"
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"]
// }