728x90

_.groupBy 는 리턴값이 같은것 끼리 array로 묶는다.

data = [
{ registrationDate: "20211201", birthday: "19920102", name:"김동현" }
,{ registrationDate: "20211210", birthday: "19920202", name:"이동현" }
,{ registrationDate: "20211225", birthday: "19920302", name:"박동현" }
,{ registrationDate: "20220102", birthday: "19930102", name:"김동수" }
,{ registrationDate: "20220112", birthday: "19930202", name:"박동수" }
,{ registrationDate: "20220122", birthday: "19930302", name:"이동수" }
,{ registrationDate: "20220122", birthday: "19930302", name:"최동수" }
]

var filterData = _.groupBy(data, function(row){ return (row.birthday.substr(0,3});

 

filterData = { 1992: Array(3), 1993:(4) };

 

 

728x90

'Javascript underscore' 카테고리의 다른 글

[underscore] 언더스코어 정리  (0) 2021.12.06
[underscore] groupBy  (0) 2021.12.06
728x90

자바스크립트의 라이브러리중 하나.

jQuery가 HTML문서를 조작하거나 DOM이벤트를 처리할 목적으로 만들어 졌다면

언더스코어는 자바스크립트를  LISP처럼 사용할 수 있게 만들어주는 라이브러리다.
매우 작은 용량에 80여가지의 function을 제공한다.

 

https://namu.wiki/w/%EC%96%B8%EB%8D%94%EC%8A%A4%EC%BD%94%EC%96%B4

 

https://harrythegreat.tistory.com/entry/%EC%96%B8%EB%8D%94%EC%8A%A4%EC%BD%94%EC%96%B4-%EC%A0%95%EB%A6%AC#%EC%96%B8%EB%8D%94%EC%8A%A4%EC%BD%94%EC%96%B4%EB%9E%80

 

javascript underscore 언더스코어 정리

언더스코어란? 용어설명 Context iteratee Context와 iteratee의 구분 Collection Functions (Arrays or Objects) each map reduce reduceRight find filter where findWhere reject every some contains invoke p..

harrythegreat.tistory.com

 

https://cyberx.tistory.com/161

 

underscore 알아보기 (2)

안녕하세요. underscore 알아보기 (1)에 이어 후속 내용을 이어가도록 하겠습니다. 이 전에 each, context(this), find, countBy, reduce, some, contains, every, max, min, sortBy, groupBy 를 알아보았습니다...

cyberx.tistory.com


 

언더스코어 선언

언더스코어 홈페이지 들어가서 라이브러리 주소를 적거나 cdn주소를 넣으면된다.

1. 홈페이지에서 라이브러리 다운 -> 프로젝트에 파일 복사 -> <script src=" 경로 "></script> 하기
2. CDN주소 선언하기 (인터넷연결이 되있어야함)

https://underscorejs.org/#

 

Underscore.js

Underscore is a JavaScript library that provides a whole mess of useful functional programming helpers without extending any built-in objects. It’s the answer to the question: “If I sit down in front of a blank HTML page, and want to start being produc

underscorejs.org

 

 

CDN이란?

라이브러리를 가져와 사용할 때는 로컬에 다운로드하거나 웹의 주소를 입력하며 됩니다.

여기서 웹 주소를 입력하는 것이 cdn입니다.
cdn은 content delivery nerwork의 약자로
웹사이트의 접속자가 콘텐츠를 다운로드할 때 자동으로 가장 가까운 서버에서 다운로드할 수 있도록 하는 기술입니다.
cdn을 사용하면 빠르게 라이브러리를 로드할 수 있습니다.

예시) 제이쿼리 CDN
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>    (구글)
<script src=
"http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.12.4.min.js"></script>         (마이크로소프트)
<script src=
"https://code.jquery.com/jquery-1.12.4.min.js"></script>                            (jquery)

셋중 맞는 버전 하나를 선언하면 된다.

 


응용 1

extend로 데이터 tepm변수에 복사한다음
allkeys로 데이터 뽑아서
filter로 데이터 있는지, if문처럼 하고
map으로 한줄씩 데이터 가공해서 표만들거나 배열 생성


_.contains(list, index, [fromIndex])

contains _.contains(list, value, [fromIndex])
	list: colletion으로써, 배열이나 객체가 될 수 있다.
	value: 배열의 element나, 객체의 value가 될 수 있다.
	[fromIndex]: list에서 value를 찾을 때, 찾기 시작하는 index이다.(생략가능)
	--> list안에 value가 있는지 확인하고, 있으면, true를 리턴한다.
    
 ex) _.contains([1, 2, 3], 3); // true

=> 간단히 말하면 첫번째 인자인 list중에 두번째인가인 value값을 찾아서 있으면 true, 없으면 false

 


_.extend(target, obj1, obj2,...)

 
 
 

 

 

응용


잘못된 예
extend할때 파라미터의 위치에 따라 결과가 달라진다.
이에 대한 내용은 아래 주소 참고
https://hyunseob.github.io/2016/07/23/underscore-extend/

_.filter(list, predicate, [context])

list : colletion으로 배열리나 객체가 될 수 있다.
predicate : list의 각 요소의 결과값이 true인지 확인하는 함수
[context] : predicate 함수에서 this로 바인딩 되는 것 (생략가능)

==> list에 담겨있는거를 차례대로 하나씩 가져와서 predicate에 선언한 함수대로 돌려서 true값을 리턴해준다.

let testNumber=[1,2,3,4,5,6];
const result = _.filter(testNumber, function(row){
                      return row % 2 == 0;
                    });
console.log(result);
//[2, 4, 6]
====================================================
let testObject = {"a":1, "b":2, "c":3, "d":4, "e":5, "f":6};
const result = _.filter(testObject, function(row){
                      return row % 2 == 0;
                 	});
console.log(result);
//[2, 4, 6]
====================================================
let testNumber=[1,2,3,4,5,6];
let context =[10,21,30,41,50,61];
console.log("testNumber = ["+testNumber+"]");
console.log("_.filter의 파라미터중 [context] = [10,21,30,41,50,61] 일때");
const result = _.filter(testNumber, function(row){
                console.log("row = "+row+", this[row] = "+this[row]);
                if(this[row] % 2 == 0){
                  console.log(this[row]+" % 2 == 0 는 true");
                }else{
                  console.log(this[row]+" % 2 == 0 는 false");
                }

                  return this[row] % 2 == 0;
                },
                context);
console.log(result);
//[2, 4]
결과:
row 는 1부터 시작해서 context의 21부터 시작하게 된다.
context는 this가 되고 this[0] = 10, this[1] = 21, this[2] = 30, ... 순서대로 된다. 



 

출처 : https://velog.io/@yunsungyang-omc/underscore.js.filter-%ED%95%A8%EC%88%98

출처 : https://medium.com/@cheonmyung0217/underscore-js-filter-%ED%95%A8%EC%88%98-51feea16b3b8


_.keys

obj의 key 반환

//_.keys(object)
_.keys({one: 1, two: 2, three: 3});
=> ["one", "two", "three"]

출처: https://harrythegreat.tistory.com/entry/언더스코어-정리 


_.allKeys

obj의 모든 inherited properties 출력

//_.allKeys(object)
function Stooge(name) {
  this.name = name;
}
Stooge.prototype.silly = true;
_.allKeys(new Stooge("Moe"));
=> ["name", "silly"]

출처: https://harrythegreat.tistory.com/entry/언더스코어-정리

출처 : https://harrythegreat.tistory.com/entry/%EC%96%B8%EB%8D%94%EC%8A%A4%EC%BD%94%EC%96%B4-%EC%A0%95%EB%A6%AC


 

 

728x90

'Javascript underscore' 카테고리의 다른 글

0209 연습  (0) 2022.02.09
[underscore] groupBy  (0) 2021.12.06
728x90

리턴값이 같은것 끼리 array로 묶는다.

//_.groupBy(list, iteratee, [context]) 

_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); }); 
=> {1: [1.3], 2: [2.1, 2.4]} 

_.groupBy(['one', 'two', 'three'], 'length'); 
=> {3: ["one", "two"], 5: ["three"]}

 

 

https://harrythegreat.tistory.com/entry/%EC%96%B8%EB%8D%94%EC%8A%A4%EC%BD%94%EC%96%B4-%EC%A0%95%EB%A6%AC

 

javascript underscore 언더스코어 정리

언더스코어란? 용어설명 Context iteratee Context와 iteratee의 구분 Collection Functions (Arrays or Objects) each map reduce reduceRight find filter where findWhere reject every some contains invoke p..

harrythegreat.tistory.com

 

728x90

'Javascript underscore' 카테고리의 다른 글

0209 연습  (0) 2022.02.09
[underscore] 언더스코어 정리  (0) 2021.12.06

+ Recent posts