자바스크립트 -map ,set , filter , slice , reduce

BackEnd_Ash.log·2020년 4월 13일
0

자바스크립트

목록 보기
11/29

https://developer.mozilla.org/
https://dongmin-jang.medium.com/javascript-15%EA%B0%80%EC%A7%80-%EC%9C%A0%EC%9A%A9%ED%95%9C-map-reduce-filter-bfbc74f0debd

slice

const arr = [1,2,3,4,5]
console.log(arr.slice(0,3)) // [ 1, 2, 3 ]
const arr = [1,2,3,4,5];
array.slice(0,2).concat(array.slice(3,5))
// [1,2,4,5]

배열 전개 연산자를 사용하면 다음과 같이 구현을 할수가 있습니다.

[...array.slice(0,2) , ...array.slice(3,5)];

filter

주어진 조건(true false) 에 통과하는 요소들을 보아 새로운 배열로 반환한다.

arr = [1,2,3,4,5]
console.log(arr.filter(num => num!==3)); // [1,2,4,5]

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter(word => word.length > 6);
console.log(result); //["exuberant", "destruction", "present"]

const number = [1,2,3,4,5].filter(num => num > 2);
console.log(number); // [ 3, 4, 5 ]

map

현재 존재하는 배열의 요소를 가져와서 ,

조건에 맞게 변경을 한다.

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1); // [ 2, 8, 18, 32 ]

let map2 = new Map([["string1" , "test1"] , ["string2" ,"test2"]])
console.log(map2); // Map(2) { 'string1' => 'test1', 'string2' => 'test2' }

Set

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

reduce

https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

arr.reduce(callback[, initialValue])

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer)); // 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5)); // 15

let arr = [9, 2, 8, 5, 7]
let sum = arr.reduce((pre, val) => pre + val)
console.log(sum)	// 31

// map
var arr = ['foo', 'hello', 'diamond', 'A']
var arr2 = arr.reduce((pre, value) => {
    pre.push(value.length)
    return pre
}, [])
console.log(arr2)   // [3, 5, 7, 1]

인자값은 callback [,initivalValue]

활용

let 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('oli'));
let 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]
profile
꾸준함이란 ... ?

0개의 댓글