본문 바로가기

WEB/내맘대로 코딩

배열메서드 - 필터링[1]

배열 필터링에 관여하는 메서드를 꼽으라면 forEach()와 filter()를 들 수 있다.

forEach()와 filter()의 사용법을 우선 간단히 비교해본다.

var singer = [];
var girls = [{name:'아이린',age:29},{name:'슬기',age:26},{name:'웬디',age:26},{name:'조이',age:23},{name:'예리',age:21}];

/* forEach()는 객체나 배열 모두 루프 실행가능하며, 지정된 범위내 값인지 조건검사하여 새로운 배열에 추가함. */
girls.forEach(function(elem){
  if( elem.age >= 23 && elem.age <= 26 ){
    singer.push( elem );
  }
});

/* 간혹 forEach()와 each()를 혼동할 수 있는데, 그 사용법이 약간 다르다. */
/* 아래처럼 사용하는 경우 //girls.each is not a function 라는 콘솔에러가 뜬다. */
girls.each(function(i,v){
  console.log(elem);
});

/* each는 jquery 요소집합만 직접 붙여 사용할 수 있음 */
$('table thead th').each(function(i,v){
  console.log(v);
});

/* 배열이나 객체에 직접 연계해서 쓰려면 $.each(array,function(){ ... }); 으로 사용해야함 */
$.each(girls, function(i,v){
  console.log(v);
});

/* filter()는 true 또는 false를 리턴하며, true 조건에 맞는 아이템을 새로운 배열에 추가함. */
singer = girls.filter(function(elem){
  return ( elem.age >=23 && elem.age <=26 );
});

jqueryUi 컴포넌트인 slider와 배열메서드 forEach()를 사용해서 나이 필터링을 구현해본다.

실행결과이다. 웬디와 예림을 위로 올렸다. 더 아끼니까 :-)

 

See the Pen yLYpYaO by rainydaymusickr (@rainydaymusickr) on CodePen.

<div class="slider">
  <div class="outer">
    <label for="age">나이 필터링</label>
	  <div class="inner">
        <input type="text" id="age" readonly>
          <span class="age-unit">세 이상</span>
        </div>
      </div>
    <div id="slider-vertical" style="height:25px;"></div>
  </div>

<table id="data-table" class="table">
<thead>
  <th>이름</th>
  <th>나이</th>
  <th>혈액형</th>
  <th>사진</th>
</thead>
</table>
:root{font-size:62.5%;}
*{margin:0;padding:0;}
body{font-size:1.6rem;}
img{height:100px;vertical-align:top;transform:scale(2);transition:all .2s ease-in;}
table{width:100%;border-collapse:collapse;border-spacing:0;}
table th{padding:1rem 0;color:#eee;background-color:teal;}
table th+th{border-left:1px solid #eee;}
table td{letter-spacing:-.1rem;text-align:center;border-bottom:1px solid #eee;overflow:hidden;}
table td:nth-child(1){background-color:yellowgreen;}
table td:nth-child(2){background-color:wheat;}
table td:nth-child(3){background-color:pink;}
table td:nth-child(4){background-color:#000;}
table td+td{border-left:1px solid #eee;}
table td:hover img{transform:scale(1.5);}
.slider{margin-bottom:2rem;}
.slider .ui-widget.ui-widget-content{margin:0 70px auto 50px;}
.slider .outer label{display:block;text-align:center;font-size:2rem;padding:1rem 0;}
.slider .outer input{width:calc(50%);height:5rem;text-align:right;font-size:3rem;border:0;}
.slider .inner {position:relative;}
.slider .inner .age-unit{position:absolute;right:0;top:50%;transform:translateY(-50%);width:50%;text-align:left;}
.slider .ui-slider .ui-slider-handle{width:4rem;height:4rem;}
.slider .ui-slider-horizontal .ui-slider-handle{top:-.8rem;}
.slider .ui-widget-header{background-color:#007fff;}
(function($){
  var singer = [];
  var $rows = [];
  var girls = [
	{name:'아이린',	age:29, blood:'A', img:'<img src="https://s3.orbi.kr/data/file/united/4c8ed5bf3e0058c4482b326e60a6541c.gif">' },
	{ name:'슬기',	age:26,	blood:'A', img:'<img src="https://i.imgur.com/c7JA2Hg.gif">'},
	{ name:'웬디',	age:26,	blood:'O', img:'<img src="https://ww.namu.la/s/0dd146e8cfb7d00e71dd298435cbfdf9b7210ecc8017afb19bfab1991ec933c2b618a1175ada15703b9dd929fe99964273c981dd7882ea47f5e6191419d07ebdd4490f2b7e841a5e9b96aa0940bd9845621283b7dfbabc6e5c4a5ec0296099dd">'},
	{ name:'조이',	age:23, blood:'A', img:'<img src="https://i.imgur.com/q94ENR0.gif">'},
	{ name:'예리',	age:21,	blood:'O', img:'<img src="https://w.namu.la/s/89694f2afaca553b215f8d013e758764b636525b89afbd6d7817660e2b45e2f2be9fe91795bbfd71193f44cbbdc861ac27e8fc6541736c1ea3d3079bfd6857e7ce1bc41d751e61a7bc42fa88f4ca5bc1733090a089170128041e16d35d5519e1">'},
	{ name:'사나',	age:23, blood:'B', img:'<img src="https://img1.daumcdn.net/thumb/R720x0.q80/?scode=mtistory2&fname=http%3A%2F%2Fcfile29.uf.tistory.com%2Fimage%2F237910445932AE3127CD04">'},
	{ name:'최예나',	age:20, blood:'A', img:'<img src="https://1.bp.blogspot.com/-n6oCsY3PbTo/XHi8-zqbBNI/AAAAAAAAOgo/g4giWdkfdvwjdzuOQZNqFqtcMO7qa01QQCLcBGAs/s1600/projectgirlgroup-20181104-172511-000.gif">'},
	{ name:'채수빈',	age:25, blood:'A', img:'<img src="https://4.bp.blogspot.com/-1otSJ33_qcQ/W-rTtcA7IWI/AAAAAAABRe0/lVLc6ytNlkcjlEYF1TAVgF1jyi1_aDeRQCLcBGAs/s1600/Honeycam%2B2018-11-13%2B22-37-15.gif">'}, 
	{ name:'박보영',	age:30, blood:'O', img:'<img src="https://2.bp.blogspot.com/-H6pTnlBBe1k/WQsnF-zc59I/AAAAAAAi0PE/Q5zoqgQOfcczewM0xZfjYkdZMxAQhEgXQCLcB/s1600/00.gif">'},
	{ name:'크리스탈',	age:25, blood:'A', img:'<img src="https://2.bp.blogspot.com/-RRYE8CE7Z94/UqV8_nX-MmI/AAAAAAAAAIg/7PutnD9rS5g/s1600/Untitled-5.gif">'}
  ];

  //girls를 테이블로 파싱
  function makeTable(){
	var $table = $('#data-table');
	var $tbody = $('<tbody></tbody>');
		
	girls.forEach(function(elem){
		var $row = $('<tr></tr>');
		$row.append( $('<td></td>').text(elem.name) );
		$row.append( $('<td></td>').text(elem.age) );
		$row.append( $('<td></td>').text(elem.blood) );
		$row.append( $('<td></td>').append(elem.img) );
		$rows.push({
			elem: elem,
			element: $row
		});
	});
	$rows.forEach(function(elem){
		$tbody.append( elem.element );
	});
	$table.append( $tbody );
  }
  makeTable();
	
  //girls data 업데이트
  function updateTable(value){
	$rows.forEach(function(row){
		if( row.elem.age >= value ){
			row.element.show();
		}else{
			row.element.hide();
		}
	});
  }
  updateTable( $("#age").val() );
  
  $( "#slider-vertical" ).slider({
	range: "min",
	min: 20,
	max: 30,
	value: 20,
	slide: function(event, ui) {
		$( "#age" ).val( ui.value );
	},
	change: function(eveny, ui){
		updateTable( ui.value );
	}
  });
  $("#age").val( $("#slider-vertical").slider("value") );
})(jQuery);

'WEB > 내맘대로 코딩' 카테고리의 다른 글

깜박임 효과  (0) 2020.12.15
배열메서드 - 필터링[2]  (0) 2020.05.05
배열메서드 - 필터링[1]  (0) 2020.05.05
선택요소 추가 및 삭제  (0) 2020.04.20
css3 효과주기  (0) 2020.04.16
틀린그림찾기  (0) 2020.04.15