gist

2012年6月14日木曜日

CoffeeScriptで学ぶ Underscore.js 08(Array編)

今回で8回目。Underscore.jsのArray編ラストです。


uniq

_.uniq(array, [isSorted], [iterator])

uniqは、指定した配列の重複を削除した配列を返します。配列がソートされている場合、isSortedをtrueにすると、より高速なアルゴリズムで重複を削除します。iteratorでは、重複とみなさない条件を指定できます。

_ = require 'underscore'

list = [4,3,2,1,2,1,4,2,3]

console.log _.uniq list

list = [1,2,2,2,3,3,4,4]
console.log _.uniq list, true

list = ["a", "a", "b", "c", "d", "d"]
console.log _.uniq list, true, (item, index, arr)->
 item is "b"

実行結果
$ coffee uniq.coffee 
[ 4, 3, 2, 1 ]
[ 1, 2, 3, 4 ]
[ 'a', 'b', 'c' ]

zip

_.zip(*arrays)

zipは、複数の配列の中の同じindexを1つの配列にまとめ(zip)、その集合を配列として返します。

_ = require 'underscore'

ids = [1,2,3,4]
names = ['折木奉太郎', '千反田える', '福部里志', '伊原摩耶花']
cvs = ['中村悠一', '佐藤聡美', '阪口大助', '茅野愛衣']

console.log _.zip ids, names, cvs
実行結果
$ coffee zip.coffee 
[ [ 1, '折木奉太郎', '中村悠一' ],
  [ 2, '千反田える', '佐藤聡美' ],
  [ 3, '福部里志', '阪口大助' ],
  [ 4, '伊原摩耶花', '茅野愛衣' ] ]

indexOf

_.indexOf(array, value, [isSorted])

indexOfは、valueで指定した値が、arrayのどのindexに位置するか返します。isSortedは、配列がソートされている場合trueを指定すると、より高速なアルゴリズムで処理します。

names = ['折木奉太郎', '千反田える', '福部里志', '伊原摩耶花']
実行結果
$ coffee indexOf.coffee 
1

lastIndexOf

_.lastIndexOf(array, value)

lastIndexOfは、indexOfが配列の先頭からvalueを走査するのに対して、配列の末から操作します。

_ = require 'underscore'

values = ['気になります', 'エコ', '気になります', 'エコ', '気になります']

console.log _.lastIndexOf values, '気になります'
実行結果
$ coffee lastIndexOf.coffee 
4

range

_.range([start], stop, [step])

rangeは、startから(stop-1)までの整数値をstep毎の集合を配列で返します。

_ = require 'underscore'

console.log _.range 10
console.log _.range 90, 100
console.log _.range 0x00, 0xff, 0x32

実行結果
$ coffee range.coffee 
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
[ 90, 91, 92, 93, 94, 95, 96, 97, 98, 99 ]
[ 0, 50, 100, 150, 200, 250 ]

関連ページ

0 件のコメント: