lodashは見ておこうと思い立ち、サイトの日本語メモを作成しました。
↓ lodashのES6で書くとこうなるというのはこちらのサイト
You Might Not Need Lodash
Array(配列操作)
_.chunk(array, [size=1])
配列を引数の数で分割する
公式)Creates an array of elements split into groups the length of size. If array can't be split evenly, the final chunk will be the remaining elements.
_.chunk(['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h'], 2);
// [["a","b"],["c","d"],["e","f"],["g","h"]]
_.compact(array)
配列の中から false
、null
、NaN
、undefined
を取り除く
公式)Creates an array with all falsey values removed. The values false, null, 0, "", undefined, and NaN are falsey.
_.compact([0, 1, false, true, null, 2, '', 3, NaN, undefined])
// [1,true,2,3]
_.concat(array, [values])
配列を連結させる
公式)Creates a new array concatenating array with any additional arrays and/or values.
let arrayA = [1, 2, 3]
let arrayB = _.concat(arrayA, 4, 5, 6)
let arrayC = _.concat(arrayA, [4, 5, 6])
arrayB // [1,2,3,4,5,6]]
arrayC // [1,2,3,4,5,6]]
let arrayD = _.concat(arrayA, [4, 5, 6, [7, 8, 9]])
arrayD // [1,2,3,4,5,6,[7,8,9]]
_.difference(array, [values])
2つの配列を比較して、含まれない値を取り出す
第一引数に比較したい配列、第二引数に比較対象となる配列を入れる
公式)Creates an array of array values not included in the other given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array.
_.difference(['花子', '太郎', '次郎', '三郎'], ['一郎', '花子'])
// ["太郎","次郎","三郎"]
_.differenceBy(array, [values], [iteratee=_.identity])
_.difference
と近い。引数に比較対象の配列と、比較する基準を入れる。
公式)This method is like _.difference except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared. The order and references of result values are determined by the first array. The iteratee is invoked with one argument:
_.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor)
// [1.2]
_.differenceBy([{ id: 1, name: '花子' }, { id: 2, name: '太郎' }, { id: 3, name: '次郎' }], [{ id: 2, access: '東京' }, { id: 3, access: '神奈川' }], 'id')
// [{ id: 1, name: '花子' }]
_.differenceWith(array, [values], [comparator])
2つの配列を比較して違う値だけを取り出す。_.differenceBy
に近いけど若干違い、比較基準を入れる。
公式)This method is like _.difference except that it accepts comparator which is invoked to compare elements of array to values. The order and references of result values are determined by the first array. The comparator is invoked with two arguments: (arrVal, othVal).
let arrayA = [{ 'id': 1, 'name': '花子' }, { 'id': 2, 'name': '太郎' }, { 'id': 3, 'name': '次郎' }];
let arrayB = [{ 'id': 1, 'name': '花子' }];
_.differenceWith(arrayA, arrayB, _.isEqual)
// [{"id":2,"name":"太郎"},{"id":3,"name":"次郎"}]
// こんな感じでも指定できる
const customComparator = (a, b) => {
return a.id === b.id && a.name === b.name
}
_.differenceWith(arrayA, arrayB, customComparator)
// [{"id":2,"name":"太郎"},{"id":3,"name":"次郎"}]
_.drop(array, [n=1])
配列から、先頭からn個分削除した配列を作る
n個指定しないとデフォルト1
公式)Creates a slice of array with n elements dropped from the beginning.
_.drop([1, 2, 3, 4, 5], 3)
// [4, 5]
_.drop([1, 2, 3, 4, 5], 5)
// []
_.dropRight(array, [n=1])
配列から、末尾からn個分削除した配列を作る
n個指定しないとデフォルト1
公式)Creates a slice of array with n elements dropped from the end.
_.dropRight([1, 2, 3, 4, 5], 2)
// [1, 2, 3]
_.dropRight([1, 2, 3, 4, 5], 5)
// []
_.dropWhile(array, [predicate=_.identity])
配列の先頭から、比較基準がfalseになるまで削除していって、
残りの配列を作る
公式)Creates a slice of array excluding elements dropped from the beginning. Elements are dropped until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).
_.dropRightWhile(array, [predicate=_.identity])
配列の末尾から、比較基準がfalseになるまで削除していって、
残りの配列を作る
公式)Creates a slice of array excluding elements dropped from the end. Elements are dropped until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).
let arrayA = [
{ 'id': 1, 'active': true },
{ 'id': 2, 'active': true },
{ 'id': 3, 'active': false },
{ 'id': 4, 'active': true },
{ 'id': 5, 'active': false },
];
_.dropWhile(arrayA, ['active', true]) // ①
_.dropWhile(arrayA, ['active', false]) // ②
_.dropRightWhile(arrayA, ['active', true]) // ③
_.dropRightWhile(arrayA, ['active', false]) // ④
// ① [{"id":3,"active":false},{"id":4,"active":true},{"id":5,"active":false}]
// ② [{"id":1,"active":true},{"id":2,"active":true},{"id":3,"active":false},{"id":4,"active":true},{"id":5,"active":false}]
// ③[{"id":1,"active":true},{"id":2,"active":true},{"id":3,"active":false},{"id":4,"active":true},{"id":5,"active":false}]
// ④ [{"id":1,"active":true},{"id":2,"active":true},{"id":3,"active":false},{"id":4,"active":true}]
_.fill(array, value, [start=0], [end=array.length])
配列を第2引数の値で埋める。
第3引数にスタート位置、第四引数に埋める数を決められる。lengthを決めるとき、最後の値は変わらない。
公式)Fills elements of array with value from start up to, but not including, end.
let array = [1, 2, 3, 4, 5]
_.fill(array, '') // ["","","","",""]
_.fill(array, 'a') // ["a","a","a","a","a"]
_.fill(Array(5), '') // ["","","","",""]
_.fill(Array(5), '2') // ["2","2","2","2","2"]
// 開始位置 1番目
// 埋めるlengthを3にした時、実際埋まるのは2つ
_.fill([2, 4, 6, 8, 10], '*', 1, 3)
// [2,"*","*",8,10]
_.findIndex(array, [predicate=_.identity], [fromIndex=0])
配列から引数に渡した比較対象に該当する値のindexを返す。
先頭から検索して一番最初に合致したindexだけ返す。
公式)This method is like _.find except that it returns the index of the first element predicate returns truthy for instead of the element itself.
_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])
_.findIndex
と使い方が同じで、末尾から検索
公式)This method is like _.findIndex except that it iterates over elements of collection from right to left.
let arrayA = [
{ 'id': 1, 'active': true },
{ 'id': 2, 'active': true },
{ 'id': 3, 'active': false },
{ 'id': 4, 'active': true },
{ 'id': 5, 'active': false },
];
// 該当する値がなかったら`-1`を返す
_.findIndex(arrayA, { 'user': '花子', 'active': false });
_.findLastIndex(arrayA, { 'user': '花子' }) // -1
_.findIndex(arrayA, { 'id': 2, 'active': true }); // 1
_.findIndex(arrayA, { 'active': false }); // 2
_.findLastIndex(arrayA, { 'active': true }) // 3
_.flatten(array)
複数ある配列から、単一レベル減らす(例を見た方が早い)
公式)Flattens array a single level deep.
let grid = [
[1, 2, 3],
[4, 5, 6],
[7, 8, 9]
]
_.flatten(grid)
// [1,2,3,4,5,6,7,8,9]
_.flattenDeep(array)
、_.flattenDepth(array, [depth=1])
_.flattenDeep
は全てのレベルがフラットになる。
_.flattenDepth
を使うと、フラットにしたいレベルの引数に指定できる。
公式)Recursively flattens array.
_.flattenDeep([1, [2, [3, [4]], 5]]);
// [1, 2, 3, 4, 5]
let array = [1, [2, [3, [4]], 5]];
_.flattenDepth(array, 1); // => [1, 2, [3, [4]], 5]
_.flattenDepth(array, 2); // => [1, 2, 3, [4], 5]
_.fromPairs(array)
2つの配列のkey、valueからオブジェクトを生成してくれる
公式)The inverse of _.toPairs; this method returns an object composed from key-value pairs.
_.fromPairs([['id', 1], ['name', '花子']]);
// {"id":1,"name":"花子"}
_.head(array)
配列の1番目の要素を取得
公式)Gets the first element of array.
_.head([1, 2, 3]); // 1
_.indexOf(array, value, [fromIndex=0])
配列から、指定したvalueに1番目に合致した値のindexを返す。
第3引数に検索スタートのindexを指定できる。負の場合は末尾から。
公式)Gets the index at which the first occurrence of value is found in array using SameValueZero for equality comparisons. If fromIndex is negative, it's used as the offset from the end of array.
_.indexOf([1, 2, 1, 2], 2) // 1
_.indexOf([1, 2, 1, 2], 2, 2) // 3
_.indexOf([1, 2, 1, 2, 1, 2, 1, 2], 2, -1) // 7
_.indexOf([1, 2, 1, 2, 1, 2, 1, 2], 3) // -1
_.initial(array)
配列の末尾だけ取り除いた、残りの配列を返す。
公式)Gets all but the last element of array.
_.initial([1, 2, 3, 4]) // [1,2,3]
_.intersection([arrays])
複数の配列から、共通の値を取得する
公式)Creates an array of unique values that are included in all given arrays using SameValueZero for equality comparisons. The order and references of result values are determined by the first array.
_.intersection([1, 2, 3], [5, 2, 1, 4], [2, 1])
// [1, 2]
_.intersectionBy([arrays], [iteratee=_.identity])
配列同士を比較する。
公式)This method is like _.intersection except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which they're compared. The order and references of result values are determined by the first array. The iteratee is invoked with one argument:
_.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// [2.1]
let arrayA = [
{ id: '1', skill: 'css' },
{ id: '2', skill: 'javascript' },
{ id: '3', skill: 'php' }
]
let arrayB = [
{ id: '4', address: '千葉' },
{ id: '5', address: '東京' },
{ id: '1', address: '神奈川' }
]
let result = _.intersectionBy(arrayA, arrayB, 'id')
result // [{"id":"1","skill":"css"}]
_.intersectionWith([arrays], [comparator])
配列を比較して合致する値を取り出す。
_.differenceWith(array, [values], [comparator])
は異なる値を取り出したのに対し、これは合致するのを取り出してくれる。
公式)This method is like _.intersection except that it accepts comparator which is invoked to compare elements of arrays. The order and references of result values are determined by the first array. The comparator is invoked with two arguments: (arrVal, othVal).
let arrayA = [{ 'id': 1, 'name': '花子' }, { 'id': 2, 'name': '太郎' }, { 'id': 3, 'name': '次郎' }];
let arrayB = [{ 'id': 1, 'name': '花子' }];
_.differenceWith(arrayA, arrayB, _.isEqual)
// [{"id":2,"name":"太郎"},{"id":3,"name":"次郎"}]
_.intersectionWith(arrayA, arrayB, _.isEqual);
// [{"id":1,"name":"花子"}]
_.join(array, [separator=','])
配列内のすべての要素を、引数の値で区切ってつなげる。
公式)Converts all elements in array into a string separated by separator.
_.join(['a', 'b', 'c'], ' - ') // a - b - c
_.last(array)
配列の最後の要素を取り出す。
公式)Gets the last element of array.
_.last([1, 2, 3]); // 3
_.lastIndexOf(array, value, [fromIndex=array.length-1])
配列の末尾から、渡したvalueにマッチする値のindexを返す。
公式)This method is like _.indexOf except that it iterates over elements of array from right to left.
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2) // 4
_.lastIndexOf([1, 2, 3, 1, 2, 3], 2, 3) // 1
_.nth(array, [n=0])
配列から、指定したインデックスの値を取り出す。負の値(-n
)で渡すと末尾からのindexになる。
公式)Gets the element at index n of array. If n is negative, the nth element from the end is returned.
let array = ['a', 'b', 'c', 'd']
_.nth(array, 1) // 'b'
_.nth(array, -1) // 'd'
_.pull(array, [values])
配列から指定して値をすべて削除した残りを返す。
公式)Removes all given values from array using SameValueZero for equality comparisons.
_.pullAll(array, values)
_.pull
とは違い、取り除く値を配列で指定できる。
公式)This method is like _.pull except that it accepts an array of values to remove.
let array = ['a', 'b', 'c', 'a', 'b', 'c'];
_.pull(array, 'a') // ["b","c","b","c"]
_.pull(array, 'a', 'b') // ["c","c"]
// NG: _.pull(array, ['a'])
_.pullAll(array, ['a']) // ["b","c","b","c"]
_.pullAll(array, ['a', 'b']) // ["c","c"]
_.pullAllBy(array, values, [iteratee=_.identity])
使い方は_.pull
と同じく、渡した値をすべて取り除いた値を返す。引数に削除したいkeyを指定。
公式)This method is like _.pullAll except that it accepts iteratee which is invoked for each element of array and values to generate the criterion by which they're compared. The iteratee is invoked with one argument: (value).
let arrayA = [
{ 'id': 1, 'address': '東京' },
{ 'id': 2, 'address': '埼玉' },
{ 'id': 3, 'address': '千葉' },
{ 'id': 4, 'address': '東京' },
];
let arrayB = [
{ 'address': '東京' }
];
_.pullAllBy(arrayA, arrayB, 'address')
// [{"id":2,"address":"埼玉"},{"id":3,"address":"千葉"}]
_.pullAllWith(array, values, [comparator])
_.pullAllBy
と使い方はほぼ一緒。
公式)This method is like _.pullAll except that it accepts comparator which is invoked to compare elements of array to values. The comparator is invoked with two arguments: (arrVal, othVal).
let arrayA = [
{ 'id': 1, 'address': '東京' },
{ 'id': 2, 'address': '埼玉' },
{ 'id': 3, 'address': '千葉' },
{ 'id': 4, 'address': '東京' },
];
let arrayB = [
{ 'id': 2, 'address': '埼玉' }
];
let arrayC = [
{ 'address': '東京' },
];
_.pullAllWith(arrayA, arrayB, _.isEqual)
// [{"id":1,"address":"東京"},{"id":3,"address":"千葉"},{"id":4,"address":"東京"}]
const customComparator = (a, b) => {
return a.address === b.address
}
_.pullAllWith(arrayA, arrayC, customComparator)
// [{"id":2,"address":"埼玉"},{"id":3,"address":"千葉"}]
_.pullAt(array, [indexes])
配列から指定したindexを取り除いた残りを返す。
公式)Removes elements from array corresponding to indexes and returns an array of removed elements.
let array = ['a', 'b', 'c', 'd', 'e', 'f'];
let pulled = _.pullAt(array, [1, 3])
pulled // ["b","d"]
array // ["a","c","e","f"]
_.remove(array, [predicate=_.identity])
公式)Removes all elements from array that predicate returns truthy for and returns an array of the removed elements. The predicate is invoked with three arguments: (value, index, array).
let array = ['foo', 27, 'man', 42, 'chew']
_.remove(array, function(el) {
return typeof el === 'number'
})
array // ["foo","man","chew"]
let enemy = [
{ id: '1', hp: 12, maxHP: 50 },
{ id: '2', hp: 0, maxHP: 50 },
{ id: '3', hp: 50, maxHP: 50 }
]
_.remove(enemy, function(e) {
return e.hp <= 0
})
enemy // [{"id":"1","hp":12,"maxHP":50},{"id":"3","hp":50,"maxHP":50}]
_.reverse(array)
配列の反転
公式)Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.
let array = [1, 2, 3]
_.reverse(array) // [3, 2, 1]
_.slice(array, [start=0], [end=array.length])
配列から、指定したindex以降の配列を返す。切り出すlengthも引数に渡せる。
公式)Creates a slice of array from start up to, but not including, end.
_.slice([1, 2, 3, 4, 5], 0, 1) // [1]
_.slice([1, 2, 3, 4, 5], 0, 3) // [1, 2, 3]
_.slice([1, 2, 3, 4, 5], 2) // [3, 4, 5]
_.sortedIndex(array, value)
第二引数の値が配列のどこに入れられるかindexを返す。
公式)Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order.
let arrayA = [10, 20, 30, 40, 50]
_.sortedIndex(arrayA, 35) // 3
_.sortedIndexBy(array, value, [iteratee=_.identity])
配列のどこに入れられるかを返す。
公式)This method is like _.sortedIndex except that it accepts iteratee which is invoked for value and each element of array to compute their sort ranking. The iteratee is invoked with one argument: (value).
let arrayB = [
{ name: '花子', age: 20 },
{ name: '太郎', age: 30 },
{ name: '二郎', age: 40 }
]
let arrayC = { name: '三郎', age: 25 }
_.sortedIndexBy(arrayB, arrayC, 'age') // 1
_.sortedIndexOf(array, value)
…どう使えば良いのか分からなかったデス。。
_.sortedUniq(array)
配列内で、隣り合う値が等しかった時重複を消してくれる。
公式)This method is like _.uniq except that it's designed and optimized for sorted arrays.
_.sortedUniq([1, 1, 2]); // [1,2]
_.sortedUniq([1, 2, 2, 2, 2, 3, 4, 4, 5]); // [1,2,3,4,5]
_.sortedUniq([2, 1, 1, 2]); // [2,1,2]
_.sortedUniq(['花子', '花子', '太郎', '太郎', '次郎', '花子']); // ["花子","太郎","次郎","花子"]
_.sortedUniqBy(array, [iteratee])
_.sortedUniq
に比較対象をセットできる。
公式)This method is like _.uniqBy except that it's designed and optimized for sorted arrays.
_.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); // [1.1, 2.3]
let array = [
{ x: 1, y: 1 },
{ x: 1, y: 1 },
{ x: 2, y: 2 },
{ x: 2, y: 2 }
]
_.sortedUniqBy(array, 'x')
// [{"x":1,"y":1},{"x":2,"y":2}]
_.tail(array)
配列の最初の要素だけ取り除いて返す。
公式)Gets all but the first element of array.
_.tail([1, 2, 3]); // [2, 3]
_.take(array, [n=1])
配列の1番目からn個目までスライスした配列を返す。
公式)Creates a slice of array with n elements taken from the beginning.
_.take([1, 2, 3, 4, 5, 6], 2); // [1, 2]
_.takeRight(array, [n=1])
末尾からn個目までスライスした配列を返す。
公式)Creates a slice of array with n elements taken from the end.
_.takeRight([1, 2, 3, 4, 5], 2); // [4, 5]
_.takeRightWhile(array, [predicate=_.identity])
配列の末尾から、指定した比較値とfalseになるまでの値を返す。
公式)Creates a slice of array with elements taken from the end. Elements are taken until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).
let arrayA = [
{ 'id': 1, 'active': true },
{ 'id': 2, 'active': true },
{ 'id': 3, 'active': false },
{ 'id': 4, 'active': true },
{ 'id': 5, 'active': false },
];
// 'active'がfalseの値を、'true'になるまで末尾から取り出す。
_.takeRightWhile(arrayA, ['active', false])
// [{"id":5,"active":false}]
// 上で出てきた`_.dropWhile`に何となく似ている。
_.dropWhile(arrayA, ['active', false])
// [{"id":1,"active":true},{"id":2,"active":true},{"id":3,"active":false},{"id":4,"active":true},{"id":5,"active":false}]
_.takeRightWhile(arrayA, ['active', true]) // []
_.takeWhile(array, [predicate=_.identity])
_.takeRightWhile
と使い方は一緒で、配列の先頭からfalseになるまで返す。
公式)Creates a slice of array with elements taken from the beginning. Elements are taken until predicate returns falsey. The predicate is invoked with three arguments: (value, index, array).
var users = [
{ 'user': 'barney', 'active': false },
{ 'user': 'fred', 'active': false },
{ 'user': 'pebbles', 'active': true }
];
_.takeWhile(users, function(o) { return !o.active; });
// => objects for ['barney', 'fred']
// The `_.matches` iteratee shorthand.
_.takeWhile(users, { 'user': 'barney', 'active': false });
// => objects for ['barney']
// The `_.matchesProperty` iteratee shorthand.
_.takeWhile(users, ['active', false]);
// => objects for ['barney', 'fred']
// The `_.property` iteratee shorthand.
_.takeWhile(users, 'active');
// => []
_.union([arrays])
配列の重複を弾きつつ、いい感じに集合した配列を返す。
公式)Creates an array of unique values, in order, from all given arrays using SameValueZero for equality comparisons.
_.union([2], [1, 2]); // [2, 1]
_.union([1, 2, 3, 4, 5, 6, 7], [5, 6, 7]) // [1,2,3,4,5,6,7]
// 変数に入れるときはこう
let array = [[1,2,3,4], [5,6,7], [], [8,9], []]
let union = _.union.apply(null, array);
union // [1,2,3,4,5,6,7,8,9]
_.unionBy([arrays], [iteratee=_.identity])
比較したいkeyをセットできる。
公式)This method is like _.union except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which uniqueness is computed. Result values are chosen from the first array in which the value occurs. The iteratee is invoked with one argument:
let arrayA = [
{ 'id': 1, 'address': '東京' },
{ 'id': 2, 'address': '埼玉' },
{ 'id': 3, 'address': '千葉' },
{ 'id': 4, 'address': '東京' },
{ 'id': 5, 'address': '埼玉' }
];
// 'address'のvalueが等しいとき、重複した値は配列の最初の値にまとめられる。
_.unionBy(arrayA, 'address')
// [{"id":1,"address":"東京"},{"id":2,"address":"埼玉"},{"id":3,"address":"千葉"}]
_.unionWith([arrays], [comparator])
_.union
と同じく、配列の重複をなくしていい感じに配列を整形してくれる。関数使える。
公式)This method is like _.union except that it accepts comparator which is invoked to compare elements of arrays. Result values are chosen from the first array in which the value occurs. The comparator is invoked with two arguments: (arrVal, othVal).
let arrayA = [
{ 'id': 1, 'address': '東京' },
{ 'id': 2, 'address': '千葉' },
{ 'id': 3, 'address': '埼玉' },
];
let arrayB = [
{ 'id': 3, 'address': '埼玉' },
{ 'id': 4, 'address': '神奈川' },
{ 'id': 5, 'address': '東京' },
]
_.unionWith(arrayA, arrayB, _.isEqual)
// [{"id":1,"address":"東京"},{"id":2,"address":"千葉"},{"id":3,"address":"埼玉"},{"id":4,"address":"神奈川"},{"id":5,"address":"東京"}]
_.uniq(array)
配列から一意な値を取得する
公式)Creates a duplicate-free version of an array, using SameValueZero for equality comparisons, in which only the first occurrence of each element is kept. The order of result values is determined by the order they occur in the array.
_.uniq([1, 2, 1, 3, 1]); // [1, 2, 3]
_.uniqBy(array, [iteratee=_.identity])
_.uniq
と使い方は一緒。引数に配列で取得したいkeyを指定できる。
公式)This method is like _.uniq except that it accepts iteratee which is invoked for each element in array to generate the criterion by which uniqueness is computed. The order of result values is determined by the order they occur in the array. The iteratee is invoked with one argument:
_.uniqBy([{ 'x': 1 }, { 'x': 2 }, { 'x': 1 }], 'x');
// [{"x":1},{"x":2}]
_.uniqBy([2.1, 1.2, 2.3], Math.floor); // [2.1, 1.2]
let objA = {
id: 1,
foreignKey: 1,
name: 'objA',
sort_order: 1
};
let objB = {
id: 2,
foreignKey: 1,
name: 'objB',
sort_order: 2
};
let objC = {
id: 1, // idがobjAと重複!
foreignKey: 1,
name: 'objB',
sort_order: 3
};
let result = _.uniqBy([objA, objB, objC], 'id');
result
// [{"id":1,"foreignKey":1,"name":"objA","sort_order":1},{"id":2,"foreignKey":1,"name":"objB","sort_order":2}]
_.uniqWith(array, [comparator])
使い方は_.uniq
と一緒。[comparator]で比較基準になる関数を入れる。
公式)This method is like _.uniq except that it accepts comparator which is invoked to compare elements of array. The order of result values is determined by the order they occur in the array.The comparator is invoked with two arguments: (arrVal, othVal).
let objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.uniqWith(objects, _.isEqual); // [{"x":1,"y":2},{"x":2,"y":1}]
let Array = [
{
id: '123',
name: 'John',
someKey: '1234'
},
{
id: '123',
name: 'John',
someKey: '12345'
}
]
let result = _.uniqWith(Array, function(arrVal, othVal) {
return arrVal.id === othVal.id;
});
// 最初の配列に集約
result // [{"id":"123","name":"John","someKey":"1234"}]
_.unzip(array)
グループ化された配列を圧縮前に再グループ化する。(例を見た方が早い。)
公式)This method is like _.zip except that it accepts an array of grouped elements and creates an array regrouping the elements to their pre-zip configuration.
// 一度`_.zip`を使って配列をグループ化する。
let zipped = _.zip(['a', 'b'], [1, 2], [true, false]);
// [['a', 1, true], ['b', 2, false]]
_.unzip(zipped);
// [["a","b"],[1,2],[true,false]]
let firstValue = [
['Tony', 42, 'passed'],
['Andrew', 19, 'failed'],
['Bart', 31, 'passed']
];
let result = _.unzip(firstValue);
result
// [["Tony","Andrew","Bart"],[42,19,31],["passed","failed","passed"]]
_.unzipWith(array, [iteratee=_.identity])
基本的には_.unzipWith
と使い方は一緒だけど、再グループ化された結果を組み合わせる方法を指定できる。
公式)This method is like _.unzip except that it accepts iteratee to specify how regrouped values should be combined. The iteratee is invoked with the elements of each group: (...group).
let zipped = _.zip([1, 2], [10, 20], [100, 200]);
_.unzipWith(zipped, _.add); // [3,30,300]
_.without(array, [values])
配列から指定された値を全て取り除いた値だけを返す。
公式)Creates an array excluding all given values using SameValueZero for equality comparisons.
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1); // [2, 3, 4]
const items = [1, 2 , 3, 4]
const itemsToRemove = [3, 4, 5]
// 下はNGな書き方!
const NGresult = _.without(items, itemsToRemove)
NGresult // [1,2,3,4]
// 下のように書きましょう
const result = _.without(items, ...itemsToRemove)
result // [1,2]
_.xor([arrays])
複数の配列から、重複している値だけ取り除いた、ユニークな値を返す。
公式)Creates an array of unique values that is the symmetric difference of the given arrays. The order of result values is determined by the order they occur in the arrays.
_.xor([2, 1], [2, 3]); // [1, 3]
var firstValue = [[1, 0, 5, 4],[1, 0, 5, 2], [1, 0, 5, 8]];
var result = _.xor(firstValue[0], firstValue[1], firstValue[2]);
result // [4,2,8]
var array1 = [1, 2, 3, 4];
var array2 = [2, 3, 4, 9];
var array3 = [1, 3, 4, 5];
_.xor (array1, array2, array3); // [9,5]
_.xorBy([arrays], [iteratee=_.identity])
_.xor
と使い方は一緒だけど、比較基準となるkeyを入れる。
公式)This method is like _.xor except that it accepts iteratee which is invoked for each element of each arrays to generate the criterion by which by which they're compared. The order of result values is determined by the order they occur in the arrays. The iteratee is invoked with one argument: (value).
_.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// [1.2, 3.4]
_.xorBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x');
// [{ 'x': 2 }]
let arrayA = [{ id: 1, busNum: '1234' }, { id: 2, busNum: '4567' }]
let arrayB = [{ id: 1, busNum: '2344' }, { id: 2, busNum: '1234' }]
let result = _.xorBy(arrayA, arrayB, 'busNum')
result // [{"id":2,"busNum":"4567"},{"id":1,"busNum":"2344"}]
_.xorWith([arrays], [comparator])
_.xor
と使い方は一緒だけど、[comparator]を入れる。
公式)This method is like _.xor except that it accepts comparator which is invoked to compare elements of arrays. The order of result values is determined by the order they occur in the arrays. The comparator is invoked with two arguments: (arrVal, othVal).
var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }];
var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }];
_.xorWith(objects, others, _.isEqual);
// [{"x":2,"y":1},{"x":1,"y":1}]
_.zip([arrays])
複数の配列の同じ順番の値を取り出し、新しい配列をグループ化してくれる。
1番目同士、2番目同士、…という感じ。
公式)Creates an array of grouped elements, the first of which contains the first elements of the given arrays, the second of which contains the second elements of the given arrays, and so on.
_.zip(['a', 'b'], [1, 2], [true, false]);
// [['a', 1, true], ['b', 2, false]]
_.zipObject([props=[]], [values=[]])
2の配列からオブジェクトを生成してくれる。
1つ目の配列にはkeyとなる値、2つ目の配列に対応する値とし、並び順に生成。
公式)This method is like _.fromPairs except that it accepts two arrays, one of property identifiers and one of corresponding values.
_.zipObject( [‘fred’, ‘barney’], [30, 40] ); // { ‘fred’: 30, ‘barney’: 40 }
_.zipObjectDeep([props=[]], [values=[]])
_.zipObject
と使い方は一緒だけど、ネストしたい配列を生成したい場合は、階層を指定できる。
公式)This method is like _.zipObject except that it supports property paths.
_.zipObjectDeep(['a.b[0].c', 'a.b[1].d'], [1, 2]);
// { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }
_.zipWith([arrays], [iteratee=_.identity])
_.zip
と使い方は一緒。配列を並び順から新しい配列を生成する時、生成後の整形について指定できる。
公式)This method is like _.zip except that it accepts iteratee to specify how grouped values should be combined. The iteratee is invoked with the elements of each group: (...group).
_.zipWith([1, 2], [10, 20], [100, 200], function(a, b, c) {
return a + b + c;
});
// [111, 222]
ここまで書いてみて(途中ヤケになってしまったけど)、正直使い所が分からないものだらけだったのですが笑、それはまだ実戦で活かしていないだけ…と信じて、
配列だけでなく他のも見ていくことにします。(心が折れかけてイマス。。)