1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

underscore.jsを使って配列を複数の条件でフィルタリング

Last updated at Posted at 2015-09-27

一覧を複数のタグでフィルタリングしたかったので、
underscore.jsを使ってやってみました。

javascript

var list = [ // 色々な女の子のリスト
	{
		name: "A子",
		tag: ["大きい","豊満","セクシー"]
	},
	{
		name: "B実",
		tag: ["小さい","ノリがいい","かわいい","頭いい"]
	},
	{
		name: "C里香",
		tag: ["スレンダー","美人","金持ち"]
	},
	{
		name: "D由紀",
		tag: ["セクシー","ノリがいい","頭いい"]
	}
];

var check = ["ノリがいい","頭いい"]; // 頭が良くて、ノリがいい子でフィルタリングしたい

var arr = []; // フィルタリングした女子のオブジェクトが格納される配列

_.each(list,function(girl,i){	 // each は配列のすべてをループする
	var jadge;
	if(check.length > 0){
		jadge = _.every(check, function(checkChild){ // every は配列のすべてが条件を許可したらtrue
				return _.find(girl.tag, function(tag){ // findは 配列が一つでも条件を満たせば、true、そこで処理をやめる
					return tag === checkChild;
				});
			});
	}else{
		jadge = false;
	}
	if(jadge){
		arr.push(girl); // jadgeがtrueのものだけを配列に格納していく
	}
});

console.log(arr); // [Object, Object] (B実とD由紀のオブジェクトが入っている)



これをvue.jsと絡めれば、結構簡単にできました。underscoreは本当に便利なので、小技をちょこちょこ載せていこうかなと。
もっと効率がいい方法があれば教えてください!

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?