티스토리 뷰

Programming language/javascript

Array/Object Method

hello-world 2019. 2. 27. 19:42
728x90
반응형

1. Array Method

 

 

Array.prototype.find()

 

"주어진 함수를 만족하는 

 첫 번째 요소의 을 반환"

 

그런 요소가 없다면 undefined 를 반환

 

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

var found = array1.find(function(element) {
  return element > 10;
});

console.log(found);

 

 

 

Array.prototype.findIndex()

 

"제공된 함수를 만족하는 배열의 

첫 번째 요소에 대한 인덱스를 반환."

 

그렇지 않으면 -1을 반환.

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

function isLargeNumber(element) {
  return element > 13;
}

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

 

 

 

Array.prototype.map()

 

"배열 내의 모든 요소에 개별로 함수가 할당,  

호출 결과를 모아 새로운 배열을 반환."

 

 

형식

map( callback

( currentValue

, index, array ), thisArg )

 

callback - 새로운 배열 요소를 생성하는 함수.  다음 세 가지 인수를 가집니다.

 

currentValue - 현재 처리할 요소

index - 처리할 현재 요소의 인덱스 ( 인수값 전달시 생략가능 )array - map() 

함수를

 호출한 배열 

인수값 전달시  생략가능 )


thisArg  

callback 함수의 this값 인수값 전달시 생략가능 )

var array1 = [1, 4, 9, 16];
// pass a function to map
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]

 

 

Array.prototype.filter()

 

"주어진 판별 함수를 통과하는 요소를 모아 

새로운 배열로 만들어 반환"

 

 

- 어떤 요소도 통과하지 못했으면 빈 배열을 반환합니다.

 

filter( callback

( element

, index, array ), thisArg )

 

callback - 새로운 배열 요소를 생성하는 함수.  다음 세 가지 인수를 가집니다.

 

element - 현재 처리할 요소

index - 처리할 현재 요소의 인덱스 ( 인수값 전달시 생략가능 )array - filter() 함수를 호출한 배열 

인수값 전달시  생략가능 )


thisArg  

callback 함수의 this값 인수값 전달시 생략가능 )

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

 

 

 

Array.prototype.every()

 

"배열 안의 모든 요소가 주어진 판별 함수를 통과하는지 테스트"

 

빈 배열에서 호출하면 무조건 true를 반환.

 

arr.every(callback[, thisArg])

 

callback - 각 요소를 시험할 함수. 다음 세 가지 인수를 받습니다.

 

currentValue - 처리할 현재 요소.

index - 처리할 현재 요소의 인덱스 ( 인수값 전달시 생략가능 )array -every 를 호출한 배열 

인수값 전달시  생략가능 )


thisArg  

callback 함수의 this값 인수값 전달시 생략가능 )

반환값 - 

이 모든 배열 요소에 대해 참(truthy)인 값을 반환하는 경우 true, 그 외엔 false.

 

const isBelowThreshold = (currentValue) => currentValue < 40;  
const array1 = [1, 30, 39, 29, 10, 13];  
console.log(array1.every(isBelowThreshold)); // expected output: true

 

 

Array.prototype.splice()

 

"배열의 기존 요소를 삭제 혹은 교체하거나

새 요소를 추가하여 배열 내용을 변경."

 

- 어떤 요소도 통과하지 못했으면 빈 배열을 반환합니다.

 

- splice( start, deletecount, item1, item2, ... )

 

start 

배열의 변경을 시작할 인덱스(초기 index : 0).  만약 배열 길이보다 길면, 실제 시작 인덱스는 배열의 길이로 설정. 

음수의 경우, 배열의 끝에서 부터 요소를 세어나가며 (초기 index : -1), 그 값의 절대값이 배열의 길이 보다 큰 경우 0으로 설정


deletecount  

배열에서 제거를 할 요소의 수. 만약 deletecount가 0의 경우, 아무런 요소도 제거되지 않는다. 

이경우, 최소한 하나의 요소를 지정해 주어야 한다. 만약, deletecount가 start에서 부터의 남은 요소 수 보다 많을 경우, 

남은 요소를 모두 제거한다.

 

item1, item2, ...

- 배열에 추가될 요소. 만약 아무런 요소도 지정하지 않는다면 삭제모드.

var months = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
// inserts at 1st index position
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'June']

months.splice(4, 1, 'May');
// replaces 1 element at 4th index
console.log(months);
// expected output: Array ['Jan', 'Feb', 'March', 'April', 'May']
var myFish = ['angel', 'clown', 'drum', mandarin', 'surgeon'];

// removes 1 element from index 3
removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

// removes 2 elements from index 0, and inserts 'parrot', 'anemone' and 'blue'
removed = myFish.splice(0, 2, 'parrot', 'anemone', 'blue');
// myFish is ['parrot', 'anemone', 'blue', 'trumpet', 'surgeon']
// removed is ['angel', 'clown']

// removes 2 elements from index 3
removed = myFish.splice(3, Number.MAX_VALUE);
// myFish is ['parrot', 'anemone', 'blue']
// removed is ['trumpet', 'surgeon']

 

 

Array.prototype.reduce()

 

"배열의 각 요소에 대해 주어진 리듀서(reducer) 

함수를 실행하고, 하나의 결과값을 반환."

 

리듀서 함수는 네 개의 인자를 가진다.

 

  1. 누산기 (acc)
  2. 현재 값 (cur)
  3. 현재 인덱스 (idx)
  4. 원본 배열 (src)

리듀서 함수의 반환 값은 누산기에 할당, 누산기는 순회 중 유지되므로 결국 최종 결과는 하나의 값으로 됨.

arr

.reduce(

callback

[,

initialValue

])

 

callback배열의 각 요소에 대해 실행할 함수. 다음 네 가지 인수를 받는다.

accumulator
누산기accmulator는 콜백의 반환값을 누적. 콜백의 이전 반환값 또는, 콜백의 첫 번째 호출이면서 initialValue를 제공한 경우에는 initialValue의 값.
currentValue
처리할 현재 요소.
currentIndex (optional - 생략가능)
처리할 현재 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작.
array (optional - 생략가능)
reduce()를 호출한 배열.

initialValue (optional - 생략가능)callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용. 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생.

//==========값 합산==========

var total = [ 0, 1, 2, 3 ].reduce(
( accumulator, currentValue ) => accumulator + currentValue,
0
);
// total is 6

//==========객체의 값 합산==========

var initialValue = 0;
var sum = [{x: 1}, {x:2}, {x:3}].reduce(
(accumulator, currentValue) => accumulator + currentValue.x
,initialValue
);

console.log(sum) // logs 6

//==========중첩배열 평탄화==========

var flattened = [[0, 1], [2, 3], [4, 5]].reduce(
( accumulator, currentValue ) => accumulator.concat(currentValue),
[]
); // [0, 1, 2, 3, 4, 5]

//==========객체내 값 인스턴스 개수 세기 ==========

var countedNames = names.reduce(function (allNames, name) {
if (name in allNames) {
allNames[name]++;
}
else {
allNames[name] = 1;
}
return allNames;
}, {});
// countedNames is:
// { 'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1 }

//==========속성으로 객체 분류하기===============
var people = [
{ name: 'Alice', age: 21 },
{ name: 'Max', age: 20 },
{ name: 'Jane', age: 20 }
];

function groupBy(objectArray, property) {
return objectArray.reduce(function (acc, obj) {
var key = obj[property];
if (!acc[key]) {
acc[key] = [];
}
acc[key].push(obj);
return acc;
}, {});
}

var groupedPeople = groupBy(people, 'age');
// groupedPeople is:
// {
// 20: [
// { name: 'Max', age: 20 },
// { name: 'Jane', age: 20 }
// ],
// 21: [{ name: 'Alice', age: 21 }]
// }

//======확장 연산자와 초기값을 이용하여 객체로 이루어진 배열에 담긴 배열 연결하기==========

var friends = [{
name: 'Anna',
books: ['Bible', 'Harry Potter'],
age: 21
}, {
name: 'Bob',
books: ['War and peace', 'Romeo and Juliet'],
age: 26
}, {
name: 'Alice',
books: ['The Lord of the Rings', 'The Shining'],
age: 18
}];

var allbooks = friends.reduce(function(accumulator, currentValue) {
return [...accumulator, ...currentValue.books];
}, ['Alphabet']);

// allbooks = [
// 'Alphabet', 'Bible', 'Harry Potter', 'War and peace',
// 'Romeo and Juliet', 'The Lord of the Rings',
// 'The Shining'
// ]

//===============중복항목 제거=======================

let arr = [1, 2, 1, 2, 3, 5, 4, 5, 3, 4, 4, 4, 4];
let result = arr.sort().reduce((accumulator, current) => {
const length = accumulator.length
if (length === 0 || accumulator[length - 1] !== current) {
accumulator.push(current);
}
return accumulator;
}, []);
console.log(result); //[1,2,3,4,5]

///========프로미스를 순차적으로 실행하기===========

/**
* 프로미스를 리턴하여 then()체이닝 실행~
* @param {array} arr - promise arr
* @return {Object} promise object
*/
function runPromiseInSequence(arr, input) {
return arr.reduce(
(promiseChain, currentFunction) => promiseChain.then(currentFunction),
Promise.resolve(input)
);
}

// promise function 1
function p1(a) {
return new Promise((resolve, reject) => {
resolve(a * 5);
});
}

// promise function 2
function p2(a) {
return new Promise((resolve, reject) => {
resolve(a * 2);
});
}

// function 3 - will be wrapped in a resolved promise by .then()
function f3(a) {
return a * 3;
}

// promise function 4
function p4(a) {
return new Promise((resolve, reject) => {
resolve(a * 4);
});
}

const promiseArr = [p1, p2, f3, p4];
runPromiseInSequence(promiseArr, 10)
.then(console.log); // 1200

 

 

2. Object Method

 

 

Object.assign()

 

"객체끼리의 손쉬운 병합 or 변경"

 

- Object.assign( target, ...sources )

 

target - 대상 객체

sources - 하나 이상의 병합 or 변경할 객체

 

const o1 = { a: 1 };
const o2 = { b: 2 };
const o3 = { c: 3 };

const obj = Object.assign(o1, o2, o3);
console.log(obj); // { a: 1, b: 2, c: 3 }
console.log(o1); // { a: 1, b: 2, c: 3 }, 대상 객체 자체가 변경됨.



const changedObj=Object.assign({}, {a:1, b:2}, {b:10})

console.log(changedObj) // { a: 1, b: 10 }, 특정 프로퍼티 변경



const addObj=Object.assign({}, {a:1, b:2}, {c:10})

console.log(changedObj) // { a: 1, b: 2, c:10 }, 프로퍼티 추가

 

 

Object.keys()

 

"개체 고유의 열거형(enumerable) 속성들을 for in루프에

의해 제공되는 순서와 동일한 순서로 리턴"

 

- Object.keys( obj ) /반환값이 배열이기에 filter, map, reduce 등으로 활용가능하니 꼬옥 기억해 두자 ~~~

 

obj - 열거형 고유 속성이 반환될 개체.

var arr = ['a', 'b', 'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// array like object
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// array like object with random key ordering
var anObj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.keys(anObj)); // ['2', '7', '100']

// getFoo is property which isn't enumerable
var myObj = Object.create({}, {
  getFoo: {
    value: function () { return this.foo; }
  }
});
myObj.foo = 1;
console.log(Object.keys(myObj)); // console: ['foo']

 

 

Object.values()

 

"객체의 key : value 구성에서 value 만 뽑아서 배열로 추출"

 

- Object.values( obj )

 

obj - 대상 객체

var obj = { foo: 'bar', baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// 유사 배열 (숫자를 속성으로 사용하는 객체)
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

 

참고 : https://developer.mozilla.org/ko/docs/Web/JavaScript/Reference/Global_Objects/Array/find

 

Array.prototype.find() - JavaScript | MDN

find() 메서드는 주어진 판별 함수를 만족하는 첫 번째 요소의 값을 반환합니다. 그런 요소가 없다면 undefined를 반환합니다.

developer.mozilla.org

 

 

 

 

 

728x90
반응형
댓글