#016 자바스크립트 200제 - Array 객체의 메소드 02
reverse() : 배열의 순서를 반대로 나열하기
- 배열을 반대로 나열. 함수 호출시 원본 배열도 변형되기 때문에 미리 고려해야 함
const str = 'abcdefghijklnmopqrstuvwxyz';
//split : 문자열을 배열로 변환, 공백없는 문자열''로 분할
//배열 요소에는 알파벳 한글자씩 넣어짐
const arr = str.split('');
console.log(arr); // ["a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "n", "m", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"]
//반대로 나열
arr.reverse(); //zyxwvutsrqpomnlkjihgfedcba
//구분자 넣기
console.log(arr.join(''));
console.log(arr.join(','));
//abcdefghijklnmopqrstuvwxyz
//z,y,x,w,v,u,t,s,r,q,p,o,m,n,l,k,j,i,h,g,f,e,d,c,b,a
some() : 배열 요소가 특정 조건을 만족하는지 확인하기
- some 메소드는 콜백 함수의 리턴값이 true를 반환할때까지만 배열 요소를 순환하고 그 다음요소부터는 처리하지 않음
- 만일 마지약 요소까지 순환해도 true를 반환하지 않으면 false를 반환함
const arr = [
{ id: 0, name: 'RED', age: 6 },
{ id: 1, name: 'ORANGE', age: 3 },
{ id: 2, name: 'YELLOW', age: 5 },
{ id: 3, name: 'GREEN', age: 2 }
];
const isYellowHere = arr.some(el => el.name == 'YELLOW');
const olderTanSix = arr.some(el => el.age > 6);
console.log(isYellowHere); //true
console.log(olderTanSix); //false
every() : 모든 배열 요소가 특정 조건을 만족하는지 확인하기
- 한번이라도 false인 경우, false 반환과 함께 실행 종료.
- 모든 결과가 true일 때만 every 메소드는 true를 반환
const arr = [
{ id: 0, name: 'RED', age: 6 },
{ id: 1, name: 'ORANGE', age: 3 },
{ id: 2, name: 'YELLOW', age: 5 },
{ id: 3, name: 'GREEN', age: 2 }
];
const isYellowHere = arr.every(el => el.name == 'YELLOW');
const youngerThanSevenAll = arr.some(el => el.age < 7);
console.log(isYellowHere); //false
console.log(youngerThanSevenAll); //true
filter() : 배열의 특정 조건을 기준으로 필터링하기
- 입력한 조건에 해당하는 요소만 필터링
- 콜백함수의 반환값은 true, false여야만 하고 이중에서 true 결과값을 만족하는 요소들만 다시 새로운 배열에 담아 반환
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
const filteredTwo = arr.filter(a => {
console.log(`현재 위치의 값은 ${a} 입니다.`);
return a % 2 == 0; // 짝수만 반환
});
console.log(filteredTwo); // [2,4,6,8,10]
const filteredThree = arr.filter(a => a % 3 == 0);
console.log(filteredThree); //[3,6,9]
find() : 배열의 특정 조건을 충족하는 요소 찾기
- 입력한 조건에 충족하는 요소만 찾음
- 콜백함수의 반환값은 true, false
const arr = [
{ name: 'RED', age: 2 },
{ name: 'ORANGE', age: 5 },
{ name: 'YELLOW', age: 30 },
{ name: 'GREEN', age: 3 },
{ name: 'GRAY', age: 6 }
];
const myColor = arr.find(a => a.age === 30);
console.log(myColor) //{ name: 'YELLOW', age: 30 }
map() : 배열 요소 일괄 변경하기
- 콜백함수를 인자로 받아, 콜백함수의 리턴으로 반환되는 값들을 재조합하여 새로운 배열을 만듦.
const arr = [
{ id: 0, name: 'RED', age: 6 },
{ id: 1, name: 'ORANGE', age: 3 },
{ id: 2, name: 'YELLOW', age: 5 },
{ id: 3, name: 'GREEN', age: 2 }
];
const arr2 = arr.map(el => {
el.age = el.age + 1;
return el;
});
const arr3 = arr.map(el => el.name);
console.log(arr2);
console.log(arr3);
//{id: 0, name: "RED", age: 7}
//{id: 1, name: "ORANGE", age: 4}
//{id: 2, name: "YELLOW", age: 6}
//{id: 3, name: "GREEN", age: 3}
//["RED", "ORANGE", "YELLOW", "GREEN"]
reduce() :
① 배열 내 값을 누적시키기
- 배열요소를 순환하면서 정의된 콜백함수에 의해 단일 값으로 누적 시킬수 있음.
배열.reduce((누적된 값, 현재요소값, 현재인덱스, 원본배열) => {
return 누적으로 반환되는 값
}, 초기값);
- 누적된 값과 현재요소값은 필수!
const numArr = [1, 2, 3, 4, 5];
const result = numArr.reduce((acc, el) => {
return acc + el;
}, 0);
console.log(result);
//15
- 초기값부터 천번째 요소에서 값을 합산 햇을때 0+1, 1+2, 3+3, 6+4, 10+5로 짐행된
- 배열의 모든요소를 순환하고 난 마지막 값이 reduce메소드의 결과값이 됨
② 중첩된 배열을 단일하게 만들기
- 배열안의 여러배열들을 단일한 배열로 만들수 있음
const arr = [1, [1,2], [4,5,6], ['배열','나열하기'], 'Jsvascript'];
const result = arr.reduce((acc, el) => {
return acc.concat(el)
},[]);
console.log(result);
// [1, 1, 2, 4, 5, 6, '배열', '나열하기', 'Javascript'];
keys : 객체에서 키만 추출하기
- 객체의 키들만 추출 가능하며 추출한 키들은 배열에 담아 반환됨
const obj = {
movie: 'Sunny',
music: 'Like stars',
style: 'Retro',
price: Infinity
};
const arr = Object.keys(obj);
console.log(arr);
// ["movie", "music","style","price"]
values : 객체에서 값만 추출하기
- 객체에서 속성의 값만 추출하고 그 값들은 배열에 담아 반환됨
const obj = {
movie: 'Sunny',
music: 'Like stars',
style: 'Retro',
price: Infinity
};
const modifiedObj = Object.entries(obj);
console.log(modifiedObj);
//[ ["movie", "Sunny"]
// ["music", "Like stars"]
// ["style", "Retro"]
// ["price", Infinity] ]
freeze : 객체 변경되지 않도록 하기
- 객체를 동결. 해당 해당 메소드를 사용한 이후에는 다른속성을 추가하거나 제거할수 없음
let obj = {};
obj.title = 'IDOL';
obj = Object.freeze(obj);
obj.title = 'Euphoria';
console.log(obj); //IDOL
const changeUntilNum = (obj, num) => {
'use strict';
while (true) {
console.log(obj);
if (obj.age >= num) {
obj = Object.freeze(obj);
}
obj.age += 1;
}
}
let profile = { name: '지연', age: 25 };
changeUntilNum(profile, 30);
//{name: "지연", age: 25}
//{name: "지연", age: 26}
//{name: "지연", age: 27}
//{name: "지연", age: 28}
//{name: "지연", age: 29}
//{name: "지연", age: 30}
//Uncaught TypeError: Cannot assign to read only property 'age' of object '#<Object>' //에러발생
seal : 객체에 속성 추가 못하게 만들기
- 객체를 봉인. 속성을 추가, 삭제할수 없음. 단, 기존속성에 대해서는 변경가능
const album = {
name: 'LOVE YOURSELF'
}
album.song = 'Euphoria';
album.singer = 'RM';
console.log(album);
//{name: "LOVE YOURSELF", song: "Euphoria", singer: "RM"}
Object.seal(album);
album.comment = 'Answer'; //봉인된 객체는 새로운 속성 추가 불가
album.singer = 'JK'; //봉인된 객체는 기존 석성에 대해 변경 가능
delete album.name; //삭제불가
console.log(album);
//{name: "LOVE YOURSELF", song: "Euphoria", singer: "JK"}
assign : 객체 병합 확장하기
- 인자로 대입된 객체들을 하나로 병합. 주의해야할 점은 첫번째 인자로 대입된 객체를 기준으로 병합
Object.assign(반환될 객체, ... 병합될 다른 객체들);
const obj1 = { one: 1, two: 2, three: 3 };
const obj2 = { name: '한라봉', age: 5, address: 'Jeju' };
const obj3 = { friends: ['혜림', '현아', '현일', '우림'] };
const newObj1 = Object.assign({}, obj1);
const newObj2 = Object.assign({}, obj1, obj2);
newObj1.four = 4;
console.log(obj1);
console.log(newObj1);
console.log(newObj2);
console.log('\n');
const newObj3 = Object.assign(obj1, obj3);
console.log(obj1);
console.log(newObj1);
console.log(newObj2);
console.log(newObj3);
// {one: 1, two: 2, three: 3}
// {one: 1, two: 2, three: 3, four: 4}
// {one: 1, two: 2, three: 3, name: "한라봉", age: 5, address: 'Jeju'}
//
// {one: 1, two: 2, three: 3, friends: ['혜림', '현아', '현일', '우림']}
// {one: 1, two: 2, three: 3, four: 4}
// {one: 1, two: 2, three: 3, name: "한라봉", age: 5, address: 'Jeju'}
// {one: 1, two: 2, three: 3, friends: ['혜림', '현아', '현일', '우림']}