LoginSignup
18
17

More than 5 years have passed since last update.

これはNextremer Advent Calendar 2016の第11日目の記事です。

はじめに

LINQが好きなのでフロントエンド、Node.jsでもLINQしたいです。
npmで何種類かありますがlinqをつかいます。

LINQとは

オブジェクトやデータベース、データセット、エンティティ、XML文書など、アプリケーションで扱うさまざまなデータソースに対して、統一的な手段でアクセスするしくみ

使用例

npm install linq

データの準備

import Enumerable from 'linq';

const objects =
    [
      { id: 1, name: 'たろう', sex: 'man', score: 100 },
      { id: 2, name: 'じろう', sex: 'man', score: 80 },
      { id: 3, name: 'さぶろう', sex: 'man', score: 40 },
      { id: 4, name: 'はなこ', sex: 'woman', score: 20 },
    ];

基本

Enumerable
    .from( objects ) //オブジェクトの準備
    .where( x => x.score >= 75 ) //75点以上でフィルタ
    .select( x => console.log( x.name ) ) //名前を表示
    .toArray(); //処理の実行(遅延処理)
//=>たろう
//=>じろう

平均点を求める

const averageScore = Enumerable
    .from( objects )
    .average( x => x.score );

console.log( averageScore );
//=>60

男女の数をかぞえる

Enumerable
    .from( objects )
    .groupBy(
        x => x.sex,
        null,
        ( key, g ) => console.log( `sex:${key} count:${g.count()}` ) )
    .toArray();
//=>sex:man count:3
//=>sex:woman count:1

ランダムに1人選ぶ

Enumerable
    .from( objects )
    .shuffle()
    .take( 1 )
    .select( x => console.log( x.name ) )
    .toArray();
//=>たろう(ランダム)

100点が存在するか

const anyPerfect = Enumerable
    .from( objects )
    .any( x=> x.score === 100 );
console.log( anyPerfect );
//=>true

idの降順で並び替えて最初のデータ

const firstOrDefault = Enumerable
    .from( objects )
    .orderByDescending( x=>x.id )
    .firstOrDefault( null, x => x );

console.log( firstOrDefault );
//=>{ id: 4, name: 'はなこ', sex: 'woman', score: 20 }

他にもメソッドは多数あります。
ここまたはここをみてください

まとめ

配列の操作が簡単かつコードが見やすくなるので積極的につかっていきたいです。

18
17
1

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
18
17