본문 바로가기

JavaScript, HTML, CSS

[JS, 코드스테이츠]02. 문자열(String Methods), 배열(Array Methods)

String클래스와 Array클래스에서 자주 사용하는 메서드 설명
- 목차
1. String Class
2. Array Methods

 

코드 스테이츠 Pre 코스 둘째 주 수강 후기.

 

 

 벌써 Pre코스의 두 번째 주가 지났다. 시간 참 빠르다.

 페어 프로그래밍에도 어느 정도 익숙해진 것 같다. 처음 페어 프로그래밍을 할 때에는 잘할 수 있을까 하는 걱정도 했었는데 그건 괜한 걱정이었고 재미있었다. 혼자서 코딩할 때랑은 다른 재미가 있음. 혼자서는 '생각> 코딩'이런 느낌으로 코딩을 하는데, 페어 프로그래밍을 하면 '생각> 정리 후 설명 / 이해한 바 확인> 코딩' 이렇게 중간중간 정리하면서 해야 하니까 기억에 더 잘 남게 된다.

 마지막 페어 프로그래밍에서는 마이크에 문제가 생겨 채팅으로 참여를 했는데 타자가 느린 편이라 엄청 힘들었다. 방법을 찾아봐야겠어.

 

 Array클래스의 filter나 map이나 reduce 등 콜백 함수가 필요한 메서드들이 정말 신기했다. 특히 줄줄이 붙여 쓸 수 있다는 점이 엄청 매력적이다. 그런 걸 메서드 체인이라고 부르는 듯. 잘 어울리는 이름이야.

 

수업 중 예제로 보여주셨던 메서드 체인.

 

 

 다 정리하고 보니 생각보다 훨씬 오래 걸렸다. 처음 접하는 개념들이 많다 보니 그런 듯하다. 그래도 한 번 싹 정리해두면 찾기 편하고 이해도 잘되니까.. 하고 위한 삼음ㅠ

 


1. String Class

· JavaScript에서 문자열은 자동으로 string형식으로 저장된다.

· str[index]와 같이 index로 문자열 하나씩 접근이 가능하지만 쓸 수는 없다(read-only).

let str = 'Ram-T';
console.log(str[0]);  //"R"
console.log(str[3]);  //"-"
console.log(str[10]);  //undefined
str[0] = 'T';
console.log(str);  //"Ram-T"

 

· +연산자를 쓸 수 있음. string타입과 다른 타입 사이에 +연산자를 쓰면 string형식으로 변환된 후 +연산자가 사용된다.

console.log('Ram' + 'T')  //"RamT"
console.log('9' + 2)  //"92"
console.log('Ram' - 'R')  //NaN: +외의 연산은 NaN이다

 

· length객체: 문자열의 전체 길이를 반환한다. 접근은 가능하지만 쓸 수는 없다(read-only).

sting클래스의 length객체는 read만 가능하다.

 

IMMUT: immutable(기존 배열 변경하지 않음) / MUT: mutable(기존 배열 변경)

메서드 특징 기능 return
str.indexOf(a) IMMUT str에 a가 있는지 찾고, 처음으로 일치하는 index를 반환. 찾고자 하는 문자열이 없으면 -1 반환. number
str.lastIndexOf(a) IMMUT indexOf와 같은 기능을 하지만 뒤에서부터 찾는다. number
str.split(a) IMMUT a를 기준으로 str을 분리한다. 분리된 문자열들을 포함한 배열을 반환. array(string으로 구성됨)
str.substring(indexStart[, indexEnd]) IMMUT string 객체의 시작 인덱스로부터 종료 인덱스 전까지 문자열의 부분 문자열을 반환. string(복사본)
str.toLowerCase() IMMUT 문자열을 소문자로 변환 string(복사본)
str.toUpperCase IMMUT 문자열을 대문자로 변환 string(복사본)
str.trim() IMMUT 문자열 양 끝의 공백을 제거. 공백이란 모든 공백문자(space, tab, NBSP 등)와 모든 개행문자(LF, CR 등)를 의미함. string(복사본)
str.match(regexp) IMMUT 문자열이 정규식과 매치되는 부분을 검색 일치하는 전체 문자열을 첫 번째 요소로 포함하는 array
str.replace(regexp | substr, newSubstr | function) IMMUT 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환.  string(복사본)

위의 표에서 밑줄이 있는 메서드는 아래에 상세 설명이 있다(클릭 시 이동).

 

 

.substring IMMUT string 객체의 시작 인덱스로부터 종료 인덱스 전까지 문자열의 부분 문자열을 반환.

구문

str.substring(indexStart[, indexEnd])

indexStart

· 반환될 문자열의 시작 인덱스.

· indexStart === indexEnd: 빈 문자열 반환.

· indexStart > indexEnd: 두 인자를 바꾼 듯 작동됨.

· indexStart < 0: 0

· indexStart > str.length: str.length

· indexStart === NaN: 0 

indexEnd

(Optional)

· 반환 문자열의 마지막 인덱스.(indexEnd는 미포함)

· 생략: 문자열의 끝까지 추출.

· indexEnd < 0: 0

· indexEnd > str.length: str.length

· indexEnd === NaN: 0

반환 값

기존 문자열의 부분 문자열.

예제

let str = '01234567';
console.log(str.substring(2, 5));  //"234"
console.log(str.substring(5, 2));  //"234"
console.log(str.substring(0, 5));  //"01234"
console.log(str.substring(-1, 10));  //"01234567"

 

 

.match IMMUT 문자열이 정규식과 매치되는 부분을 검색

구문

str.match(regexp)

regexp

· 정규식 개체. RegExp가 아닌 객체 obj가 전달되면, new RegExp(obj)를 사용하여 암묵적으로 RegExp로 변환됨.

· 매개변수를 전달하지 않고 match()를 사용하면, 빈 문자열이 있는 Array를 반환.

반환 값

· 문자열이 정규식과 일치하면, 일치하는 전체 문자열을 첫 번째 요소로 포함하는 Array를 반환.

· 일치하는 것이 없으면 null 반환.

RegExp 정규식 패턴을 사용한 텍스트 판별에 사용할 정규 표현식 객체를 생성함.

자세한 사항은 아래의 링크 참조(MDN정규 표현식)

https://developer.mozilla.org/ko/docs/Web/JavaScript/Guide/%EC%A0%95%EA%B7%9C%EC%8B%9D

 

정규 표현식

정규 표현식은 문자열에 나타는 특정 문자 조합과 대응시키기 위해 사용되는 패턴입니다. 자바스크립트에서, 정규 표현식 또한 객체입니다.  이 패턴들은 RegExp의 exec 메소드와 test 메소드  ,그리고 String의  match메소드 , replace메소드 , search메소드 ,  split 메소드와 함께 쓰입니다 . 이 장에서는 자바스크립트의 정규식에 대하여 설명합니다.

developer.mozilla.org

예제

let paragraph = 'The quick brown fox jumps over the lazy dog. It barked.';
let regex = /[A-Z]/g;
let found = paragraph.match(regex);

console.log(found);  //Array ["T", "I"]

paragraph = 'For more information, see Chapter 3.4.5.1';
regex = /see (chapter \d+(\.\d)*)/i;
found = paragraph.match(regex);

console.log(found);  //Array ["see Chapter 3.4.5.1", "Chapter 3.4.5.1", ".1"]

의문: 아래의 코드는 왜 원하는 대로 되지 않는 걸까?

'see chapter'를 우선으로 찾고, 그 뒤에 숫자.숫자.숫자...가 오는 문장들이 return되어야 하는 것 아닌가??

이건 질문 후 답변을 받아 다시 정리해야겠다. 정규식 어렵군.

let paragraph = 'For more information, see Chapter 3.4.5.1, see chapter 2.7.4';
let regex = /see chapter \d+[\.\d]*/i;
let found = paragraph.match(regex);

console.log(found);
/*
기대한 Array ["see Chapter 3.4.5.1", "see chapter 2.7.4"]
실제 Array ["see Chapter 3.4.5.1"]
*/

 

 

.replace IMMUT 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열을 반환. 그 패턴은 문자열이나 정규식(RegExp)이 될 수 있으며, 교체 문자열은 문자열이나 모든 매치에 대해서 호출된 함수일 수 있음.

구문

str.replace(regexp | substr, newSubstr | function)

pattern regexp 정규식객체 또는 리터럴. 일치하는 항목은 newSubStr 또는 지정된 함수가 반환 한 값으로 대체됨.
substr newSubStr로 대체 될 String. 정규식이 아닌 글자 그대로의 문자열로 처리됩니다. 오직 첫 번째 일치되는 문자열만이 교체됨.
replacement newSubstr 바꿀 문자열. 여러가지 대체 패턴들이 지원됨.
function 일치하는 요소를 대체하는 데 사용될 새 하위 문자열을 생성하기 위해 호출되는 함수.
반환 값 어떤 패턴에 일치하는 일부 또는 모든 부분이 교체된 새로운 문자열.

예제

let p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
let regex = /dog/gi;

console.log(p.replace(regex, 'ferret'));
//"The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?"

console.log(p.replace('dog', 'monkey'));
//"The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?"

console.log(p)
//"The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?"

 

 


2. Array Methods

· length객체: 배열의 길이를 반환한다. 접근과 수정이 가능하다.

array클래스의 length객체는 수정이 가능하다.

 

IMMUT: immutable(기존 배열 변경하지 않음) / MUT: mutable(기존 배열 변경)

메서드 특징 기능 return
arr.isArray(a) IMMUT a가 배열이면 true, 아니면 false를 반환. boolean
arr.push(a) MUT 배열 마지막에 a를 추가. push 후 배열의 길이(number)
arr.pop() MUT 배열 마지막 요소 제거. 제거된 element
arr.join([separator]) IMMUT arr의 요소들을 string으로 연결해서 반환. 연결자(separator)가 있을 경우 연결자로 연결됨. string
arr.indexOf(a[, fronIdex]) IMMUT

배열 내 a와 일치하는 요소의 위치 반환. fromIndex는 찾기 시작하는 위치. 중복일 경우 가장 앞쪽(0과 가까운) 인덱스. 존재하지 않으면 -1.

number
arr.includes(a[, fronIdex]) IMMUT 배열이 특정 요소를 포함하고 있는지 판별(대소문자 구분함) boolean
arr.find(callback(element[[, index], array])[, thisArg]) IMMUT callback을 만족하는 첫 번째 요소의 값 반환. 만족하는 요소가 없다면 undefined 반환. 요소의 값, undefined
arr.concat([value1[, value2[, ...]]]) IMMUT 인자로 주어진 배열이나 값들을 기존 배열에 합쳐서 새 배열을 반환. 얕은 복사. 새로운 array(복사본)
arr.every(callback(currentValue[, idx[, array]])[, thisArg]) IMMUT 배열 안의 모든 요소가 callback을 통과하는지 테스트함. callback이 모든 요소에 대해 참을 반환하는 경우 true, 그 외에 false 반환. boolean
arr.some(callback(currentValue[, idx[, array]])[, thisArg]) IMMUT 배열 안의 어떤 요소라도 주어진 판별 함수를 통과하는지 테스트함. callback이 어떤 요소에 대해서라도 참을 반환하는 경우 true, 그 외에 false 반환. boolean
arr.fill(a[, start[, end]]) MUT 배열의 start 인덱스부터 end 인덱스의 이전까지를 a값으로 채움. 변형된 array(원본)
arr.shift MUT 배열의 첫 번째 요소를 제거. 제거된 요소
arr.unshift([...a]) MUT 배열의 맨 앞쪽에 새로운 요소(a) 추가. 변경된 length속성(number)
arr.reverse() MUT 배열의 순서를 반전합니다. 첫 번째 요소는 마지막 요소가 되며 마지막 요소는 첫 번째 요소가 됨. 순서가 반전된 array(원본)
arr.slice([begin[, end]]) IMMUT 배열의 begin부터 end(end 미포함)까지에 대한 얕은 복사본을 새로운 배열 객체로 반환. 추출한 요소를 포함한 새로운 array
arr.splice(start[, deleteCount[, item1[, ...]]) MUT 배열의 기존 요소를 삭제 or 교체 or 새 요소를 추가하여 배열의 내용 변경. 제거한 요소를 담은 arrray
arr.sort([compareFunction(a, b)]) MUT 배열의 요소를 정렬한 후 그 배열을 반환. 정렬한 array(원본)
arr.filter(callback(element[, index[, array]])[, thisArg]) IMMUT 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환. 테스트를 통과한 요소로 이루어진 새로운 array
arr.forEach(callback(currentValue[, idex[, array]])[, thisArg]); IMMUT 주어진 함수를 배열 요소 각각에 대해 실행. undefined
arr.map(callback(currentValue[, index[, array]])[, thisArg]) IMMUT 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환. callback의 결과를 모은 새로운 array
arr.reduce(callback(accumulator, curruntValue[, currentIndex[, array]])[, initalValue]) IMMUT 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과 값을 반환. 누적 계산의 결과 값

위의 표에서 밑줄이 있는 메서드는 아래에 상세 설명이 있다(클릭 시 이동).

 

 

.slice IMMUT 배열의 begin부터 end(end 미포함)까지에 대한 얕은 복사본을 새로운 배열 객체로 반환.

구문

arr.slice([begin[, end]])

begin

(Optional)

· 추출 시작점에 대한 인덱스(0부터 시작).

· 음수 인덱스: 배열의 끝에서부터의 길이. slice(-2)는 배열에서 마지막 두 개의 엘리먼트를 추출.

· begin이 undefined: 0번 인덱스부터 slice.

· begin이 배열의 길이보다 큼: 빈 배열 반환.

end

(Optional)

· 추출을 종료할 인덱스(0부터 시작). slice는 end인덱스는 제외하고 추출함.

· 음수 인덱스: 배열의 끝에서부터의 길이. slice(2, -1)는 세 번째부터 끝에서 두 번째 요소까지 추출.

· end 생략: 배열의 끝까지(arr.length) 추출.

· end값이 배열의 길이보다 큼: 배열의 끝까지(arr.length) 추출.

반환 값

추출한 요소를 포함한 새로운 배열.

설명

· slice메서드를 사용하더라도 원본에는 영향이 없음.

· start > end의 경우 빈 배열 반환.

 

예제

let animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];

console.log(animals.slice());  //Array ["ant", "bison", "camel", "duck", "elephant"]
console.log(animals.slice(2));  //Array ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4));  //Array ["camel", "duck"]
console.log(animals.slice(10));  //Array []
console.log(animals.slice(undefined, -3));  //Array ["ant", "bison"]
console.log(animals.slice(-3, 9));  //Array ["camel", "duck", "elephant"]
console.log(animals.slice(3, 0));  //Array []

 

 

.splice MUT 배열의 기존 요소를 삭제 or 교체 or 새 요소를 추가하여 배열의 내용 변경.

구문

arr.splice(start[, deleteCount[, item1[, item2[, ...]]]])

start

· 배열의 변경을 시작할 인덱스.

· 배열의 길이보다 큰 값: 배열의 길이.

· 음수: 배열의 끝에서부터의 길이. (-n) === (arr.length - n)

  - (n > arr.length): 0으로 설정

deleteCount (Optional)

· 제거할 요소의 수

· deleteCount 생략 / 값이 arr.length - start보다 큼: start부터의 모든 요소 제거

· deleteCount <= 0: 어떤 요소도 제거하지 않음. 이 때는 최소한 하나의 새로운 요소를 지정해야 함

item1, item2, ... (Optional)

· 배열에 추가할 요소.

· 아무 요소도 지정하지 않음: 요소를 제거하기만 함

반환 값 제거한 요소를 담은 배열. 하나의 요소만 제거한 경우 길이가 1인 배열 반환.

예제

let months = ['Jan', 'March', 'April', 'June'];

console.log(months.splice(1, 0, 'Feb'));  //Array []
console.log(months);  //Array ['Jan', 'Feb', 'March', 'April', 'June']
console.log(months.splice(4, 1, 'May'));  //Array ["June"]
console.log(months);  //Array ['Jan', 'Feb', 'March', 'April', 'May']
console.log(months.splice(4, 1));  //Array ["May"]
console.log(months);  //Array ['Jan', 'Feb', 'March', 'April']
console.log(months.splice(0));  //Array ["Jan", "Feb", "March", "April"]
console.log(months);  //Array []

 

 

.sort MUT 배열의 요소를 정렬한 후 그 배열을 반환.

구문

arr.sort([compareFunction(a, b)])

compareFunction(a, b)

· 정렬 순서를 정의하는 함수.

· 생략: 기본 정렬 순서인 문자열의 유니코드 코드 포인트 값에 따라 정렬됨.

· return < 0 : a를 b보다 낮은 색인으로 정렬.

· return === 0 : a와 b를 변경하지 않고 넘어감. 

· return > 0 : b를 a보다 낮은 인덱스로 정렬.(a와 b의 위치 바꿈)

· 특정 쌍이 두 개의 인수로 주어질 때 항상 동일한 값을 출력하지 않으면 정렬 순서가 정의되지 않음.

반환 값 정렬한 배열(원본).

예제

let array1 = [1, 30, 4, 21, 100000];

console.log((array1 === array1.sort()))  //true
console.log((array1 === array1.concat()))  //false

console.log(array1);  //Array [1, 100000, 21, 30, 4]

array1.sort(function(a, b){	//오름차순 정렬
  if(a < b){
    return -1; //a가 b보다 낮은 index
  }
  else if(a > b){
    return 1; //a가 b보다 높은 index
  }
  else{
    return 0; //index변경 없음
  }
});
console.log(array1);  //Array [1, 4, 21, 30, 100000]

let array2 = [1, 30, 4, 21, 100000];
array2.sort(function(a, b){ //내림차순 정렬
  return b-a;
  //return값이 0인지, 0보다 큰지, 0보다 작은지만 비교하기 때문에 이렇게 간단하게 쓸 수 도 있다.
});
console.log(array1);  //Array [100000, 30, 21, 4, 1]

 

 

.filter() IMMUT 주어진 함수의 테스트를 통과하는 모든 요소를 모아 새로운 배열로 반환.

구문

arr.filter(callback(element[, index[, array]])[, thisArg])

callback(element[, index[, array]]) 각 요소를 시험할 함수. true를 받으면 유지, false를 받으면 버림. 아래 세 가지 매개변수를 받음.
  element 처리할 현재 요소.
Optional index  처리할 요소의 인덱스.
Optional array filter()를 호출한 배열. 순회(traverse)되는 배열 객체.
thisArg (Optional) callback을 실행할 때 this로 사용하는 값.
반환 값 테스트를 통과한 요소로 이루어진 새로운 배열. 통과한 요소가 없으면 빈 배열을 반환.

설명

· callback은 할당된 값이 있는 배열의 인덱스에 대해서만 호출.

 - 삭제됐거나 값이 할당된 적 없는 인덱스에 대해서는 호출되지 않음.

· thisArg 매개변수가 제공된 경우, callback의 this값으로 전달됨.

· 요소의 범위는 callback의 첫 호출 전에 설정됨.

 - 호출 이후에 추가된 요소는 callback에 의해 방문되지 않음.

 - 배열의 기존 요소가 변경 또는 삭제된 경우

   : callback에 전달된 그 값은 filter()가 그 요소를 방문한 시점의 값을 사용. 삭제된 요소는 반영되지 않음.

     반복 중 배열이 변경되면 다른 요소들을 건너뛸 수도 있음.

   : 예제를 돌려 보니 메서드가 실행되는 순간 사용할 배열(의 시작 주소?)과 index가 지정되는 메커니즘인 듯. 인덱스는 지정이되 배열은 시작 주소만 지정되는 것이기 때문에 callback도중 배열의 내용이 바뀌면 바뀌는 대로 그에 맞게 callback이 실행된다.

 

예제

let words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];

let result = words.filter(word => word.length > 6);
console.log(result);  //Array ["exuberant", "destruction", "present"]

result = words.filter(function(element, idx){
 //element와 idx를 보고 싶을 경우 아래 주석 해제
 //console.log('element: ' + element + ' /idx: ' + idx);
 if(idx === 1){
  words.pop();
 }
 return element.length > 6;
});
console.log(result);  //Array ["exuberant", "destruction"]

words.unshift('property');  //Array ["property", "spray", "limit", "elite", "exuberant", "destruction"]
result = words.filter(function(element){
  console.log('element: ' + element);
 if(element === 'spray'){
  words.shift();
 }
 return element.length > 6;
});
/*
> "element: property"
> "element: spray"
> "element: elite"
> "element: exuberant"
> "element: destruction"
*/
console.log(result);  //Array ["exuberant", "destruction"]

result = words.filter(function(element){
 if(element === 'spray'){
  words.push('prototype');
 }
 return element.length > 6;
});
console.log(result);  //Array ["exuberant", "destruction"]

console.log(words);  //Array ["spray", "limit", "elite", "exuberant", "destruction", "prototype"]
result = words.filter(function(element){
 if(element === 'spray'){
  words[2] = 'brilliant';
 }
 return element.length > 6;
});
console.log(result);  //Array ["brilliant", "exuberant", "destruction", "prototype"]

 

 

.forEach IMMUT 주어진 함수를 배열 요소 각각에 대해 실행.

구문

arr.forEach(callback(currentValue[, idex[, array]])[, thisArg]);

callback(currentValue[, idex[, array]]) 각 요소에 대해 실행할 함수. 아래 세 가지 매개변수를 받음.
  currentValue 처리할 현재 요소.
Optional index  처리할 요소의 인덱스.
Optional array forEach()를 호출한 배열.
thisArg (Optional) callback을 실행할 때 this로 사용하는 값.
반환 값 undefined

설명

· 주어진 callback을 배열에 있는 각 요소에 대해 오름차순으로 한 번씩 실행. 삭제했거나 초기화하지 않은 인덱스 속성에 대해서는 실행하지 않음.

· thisArg 매개변수가 제공된 경우, callback의 this값으로 전달됨.

· 요소의 범위는 callback의 첫 호출 전에 설정됨.

 - 호출 이후에 추가된 요소는 callback에 의해 방문되지 않음.

 - 배열의 기존 요소가 변경 또는 삭제된 경우

   : callback에 전달된 그 값은 forEach()가 요소를 방문한 시점의 값을 사용. 방문 전 삭제된 요소는 방문하지 않음.

     반복 중 배열이 변경되면 다른 요소들을 건너뛸 수도 있음.

· map()과 reduce()와는 달리 undefinded를 반환하기 때문에 메서드 체인의 중간에 사용할 수 없음.

 - 대표적 사용처: 메서드 체인 끝에서 side effect를 실행

 

예제

let items = ['item1', 'item2', 'item3', 'item4'];
let copy = [];

items.forEach(function(item){
  copy.push(item);
});
console.log(copy);  //Array ["item1", "item2", "item3", "item4"]

items.forEach(function(item) {
  console.log(item);
  if (item === 'item2') {
    items.shift();
  }
});
/*
> "item1"
> "item2"
> "item4"
*/
console.log(items);  //Array ["item2", "item3", "item4"]

 

 

.map IMMUT 배열 내의 모든 요소 각각에 대하여 주어진 함수를 호출한 결과를 모아 새로운 배열을 반환.

구문

arr.map(callback(currentValue[, index[, array]])[, thisArg])

callback(currentValue[, index[, array]]) 각 요소에 대해 실행할 함수. 아래 세 가지 매개변수를 받음.
  currentValue 처리할 현재 요소.
Optional index  처리할 요소의 인덱스.
Optional array map()을 호출한 배열.
thisArg (Optional) callback을 실행할 때 this로 사용하는 값.
반환 값 배열의 각 요소에 대해 실행한 callback의 결과를 모은 새로운 배열

예제

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

let kvArray = [{key:1, value:10},
               {key:2, value:20},
               {key:3, value: 30}];
let reformattedArray = kvArray.map(function(obj){ 
   let rObj = {};
   rObj[obj.key] = obj.value;
   return rObj;
});
console.log(reformattedArray);
//Array [Object { 1: 10 }, Object { 2: 20 }, Object { 3: 30 }]

 

 

.reduce IMMUT 배열의 각 요소에 대해 주어진 리듀서(reducer) 함수를 실행하고, 하나의 결과 값을 반환.

구문

arr.reduce(callback(accumulator, curruntValue[, currentIndex[, array]])[, initalValue])

callback(accumulator, currentValue[, currentIndex[, array]]) 각 요소에 대해 실행할 함수. 아래 네 가지 매개변수를 받음.
  accumulator

· 누산기. callback의 반환 값을 누적함.

· callback의 첫 번째 호출

 - initialValue 없음: accumulator === arr[0]  //currentIndex === 1

 - initialValue를 제공한 경우: accumulator === initialValue  //currentIndex === 0

  currentValue 처리할 현재 요소.
Optional currentIndex  처리할 요소의 인덱스. initialValue를 제공한 경우 0, 아니면 1부터 시작함.
Optional array reduce()를 호출한 배열.
initialValue (Optional)

· callback의 최초 호출에서 첫 번째 인수에 제공하는 값. 초기값을 제공하지 않으면 배열의 첫 번째 요소를 사용. 

· 빈 배열에서 초기값 없이 reduce()를 호출하면 오류가 발생

반환 값 누적 계산의 결과 값

예제

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

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

let flattened = [[0, 1], [2, 3], [4, 5]].reduce(
  function(accumulator, currentValue) {
    return accumulator.concat(currentValue);
  }, []);
console.log(flattened);  //Array [0, 1, 2, 3, 4, 5]

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