본문 바로가기
개발/javascript

lodash Array 메서드 a to z - ( return Array )

by 올럭Dev 2023. 10. 31.
728x90

목차 📑

  • lodash Array 메서드 소개
  • lodash Array 메서드 a to z

lodash Array 메서드 소개

Lodash Array 메서드를 한번씩 사용해보겠습니다.

lodash 공식 홈페이지
lodash 연습장

lodash Array 메서드 a to z

c

_.chunk(array, [size=1])

원본 배열을 size만큼 잘라 새로운 배열을 반환합니다.
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.

const chunk1 = _.chunk(["a", "b", "c", "d", "e"], 2);
// => [['a', 'b'], ['c', 'd']]  

const chunk2 = _.chunk(["a", "b", "c", "d"], 3);
// => [['a', 'b', 'c'], ['d']]

_.compact(array)

원본 배열에서 falsey (false, null, 0, “”, undefined, and NaN) 값들을 제외시킨 새로운 배열을 반환합니다.
Creates an array with all falsey values removed. The values false, null, 0,“”, undefined, and NaN are falsey

const compact = _.compact([0, 1, false, 2, "", 3]);
// => [1, 2, 3]

_.concat(array, [values])

원본 배열에 값들을 합쳐 새로운 배열을 반환합니다.
Creates a new array concatenating array with any additional arrays and/or values.

var array = [1];
var concat = _.concat(array, 2, [3], [[4]]);  

console.log(concat);
// => [1, 2, 3, [4]]
console.log(array);
// => [1]

d

_.difference(array, [values]) <> _.pullAll()

원본 배열에만 있는 값을 새로운 배열로 반환합니다.
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.
Note: Unlike _.pullAll, this method returns a new array.

const a = [2, 1];
const difference = _.difference([2, 1, 2], [2, 3]);
// => [1]

console.log("difference : ", difference);

_.differenceBy(array, [values], [iteratee=_.identity]) <>_.pullAllBy()

원본 배열에만 있는 값을 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
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.
Note: Unlike _.pullAllBy, this method returns a new array.

const differenceBy1 = _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [1.2] 

// The `_.property` iteratee shorthand.
const differenceBy2 = _.differenceBy(
[{ x: 2 }, { x: 1 }],
[{ x: 1 }],
"x"
);
// => [{ 'x': 2 }]

_.differenceWith(array, [values], [comparator]) <>_.pullAllWith()

원본 배열에만 있는 값을 새로운 배열로 반환합니다.
✨ 메서드명에 -With가 붙으면 내부 로직을 변경할 수 있습니다.
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).
Note: Unlike _.pullAllWith, this method returns a new array.

var objects = [
{ x: 1, y: 2 },
{ x: 2, y: 1 }
]; 

const differenceWith = _.differenceWith( 
	objects,
	[{ x: 1, y: 2 }],
	_.isEqual
	);
// => [{ 'x': 2, 'y': 1 }]

_.drop(array, [n=1])

원본 배열을 앞에서부터 n만큼 잘라내고 새로운 배열로 반환합니다.
Creates a slice of array with n elements dropped from the beginning.

const drop1 = _.drop([1, 2, 3]);
// => [2, 3] 

const drop2 = _.drop([1, 2, 3], 2);
// => [3] 

const drop3 = _.drop([1, 2, 3], 5);
// => [] 

const drop4 = _.drop([1, 2, 3], 0);
// => [1, 2, 3]  

_.dropRight(array, [n=1])

원본 배열을 뒤에서부터 n만큼 잘라내고 새로운 배열로 반환합니다.
Creates a slice of array with n elements dropped from the end.

const dropRight1 = _.dropRight([1, 2, 3]);
// => [1, 2] 

const dropRight2 = _.dropRight([1, 2, 3], 2);
// => [1] 

const dropRight3 = _.dropRight([1, 2, 3], 5);
// => [] 

const dropRight4 = _.dropRight([1, 2, 3], 0);
// => [1, 2, 3]

_.dropRightWhile(array, [predicate=_.identity]) ≈ filter()와 비슷

원본 배열을 뒤에서부터 predicate가 true이면 잘라내고 새로운 배열로 반환합니다.
✨ 메서드명에 -While이 붙으면 내부 로직을 변경할 수 있습니다.
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).

var users = [
{ user: "barney", active: true },
{ user: "fred", active: false },
{ user: "pebbles", active: false }
]; 

const dropRightWhile1 = _.dropRightWhile(users, function (o) {
	return !o.active;
});
// => objects for ['barney'] 

// The `_.matches` iteratee shorthand.
const dropRightWhile2 = _.dropRightWhile(users, {
	user: "pebbles",
	active: false
	});
// => objects for ['barney', 'fred'] 

// The `_.matchesProperty` iteratee shorthand.
const dropRightWhile3 = _.dropRightWhile(users, ["active", false]);
// => objects for ['barney'] 

// The `_.property` iteratee shorthand.
const dropRightWhile4 = _.dropRightWhile(users, "active");
// => objects for ['barney', 'fred', 'pebbles']

_.dropWhile(array, [predicate=_.identity]) ≈ filter()와 비슷

원본 배열을 앞에서부터 predicate가 true이면 잘라내고 새로운 배열로 반환합니다.
✨ 메서드명에 -While이 붙으면 내부 로직을 변경할 수 있습니다.
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).

var users = [
{ user: "barney", active: true },
{ user: "fred", active: false },
{ user: "pebbles", active: false }
]; 

const dropRightWhile1 = _.dropRightWhile(users, function (o) {
	return !o.active;
});
// => objects for ['barney'] 

// The `_.matches` iteratee shorthand.
const dropRightWhile2 = _.dropRightWhile(users, {
	user: "pebbles",
	active: false
	});
// => objects for ['barney', 'fred'] 

// The `_.matchesProperty` iteratee shorthand.
const dropRightWhile3 = _.dropRightWhile(users, ["active", false]);
// => objects for ['barney'] 

// The `_.property` iteratee shorthand.
const dropRightWhile4 = _.dropRightWhile(users, "active");
// => objects for ['barney', 'fred', 'pebbles']

f

_.fill(array, value, [start=0], [end=array.length])

원본 배열의 사이즈만큼 값을 채워 원본 배열을 업데이트합니다.
Fills elements of array with value from start up to, but not including, end.

var array = [1, 2, 3]; 

const fill1 = _.fill(array, "a");
console.log(array);
// => ['a', 'a', 'a']  

const fill2 = _.fill(Array(3), 2);
// => [2, 2, 2]  

const fill3 = _.fill([4, 6, 8, 10], "*", 1, 3);
// => [4, '*', '*', 10]

_.findIndex(array, [predicate=_.identity], [fromIndex=0])

원본 배열에서 predicate에 해당하는 첫번째 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.find except that it returns the index of the first element predicate returns truthy for instead of the element itself.

var users = [
{ user: "barney", active: false },
{ user: "fred", active: false },
{ user: "pebbles", active: true }
];
 
const findIndex0 = _.findIndex(users, function (o) {
	return o.user == "noUser";
});
// 없으면 -1  

const findIndex1 = _.findIndex(users, function (o) {
	return o.user == "barney";
});
// => 0 

// The `_.matches` iteratee shorthand.
const findIndex2 = _.findIndex(users, { user: "fred", active: false });
// => 1  

// The `_.matchesProperty` iteratee shorthand.
const findIndex3 = _.findIndex(users, ["active", false]);
// => 0  

// The `_.property` iteratee shorthand.
const findIndex4 = _.findIndex(users, "active");
// => 2

_.findLastIndex(array, [predicate=_.identity], [fromIndex=array.length-1])

원본 배열에서 predicate에 해당하는 마지막 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.findIndex except that it iterates over elements of collection from right to left.

var users = [
{ user: "barney", active: true },
{ user: "fred", active: false },
{ user: "pebbles", active: false }
];  

const findLastIndex1 = _.findLastIndex(users, function (o) {
	return o.user == "pebbles";
});
// => 2  

// The `_.matches` iteratee shorthand.
const findLastIndex2 = _.findLastIndex(users, {
	user: "barney",
	active: true
});
// => 0 

// The `_.matchesProperty` iteratee shorthand.
const findLastIndex3 = _.findLastIndex(users, ["active", false]);
// => 2

// The `_.property` iteratee shorthand.
const findLastIndex4 = _.findLastIndex(users, "active");
// => 0

_.flatten(array)

원본 배열에 요소를 꺼내 새로운 배열로 반환합니다.
Flattens array a single level deep.

const flatten1 = _.flatten([1, [2, [3, [4]], 5]]);
// => [1, 2, [3, [4]], 5]  

const flatten2 = _.flatten([1, 2, [3, 4]]);
// => [1, 2, 3, 4]  

const flatten3 = _.flatten([1, 2, [3, 4], { age: 17 }]);
// => [1, 2, 3, 4, {age: 17}]

_.flattenDeep(array)

원본 배열에 깊이 상관 없이 요소를 꺼내 새로운 배열로 반환합니다.
Flattens array a single level deep.

const flattenDeep = _.flattenDeep([1, [2, [3, [4]], 5]]);
// => [1, 2, 3, 4, 5]

_.flattenDepth(array, [depth=1])

원본 배열에 depth 깊이까지 요소를 꺼내 새로운 배열로 반환합니다.
Recursively flatten array up to depth times.

var array = [1, [2, [3, [4]], 5]]; 

const flattenDepth1 = _.flattenDepth(array, 1);
// => [1, 2, [3, [4]], 5] 

const flattenDepth2 = _.flattenDepth(array, 2);
// => [1, 2, 3, [4], 5]

_.fromPairs(pairs) <>_.toPairs() 와 반대

원본 배열을 key, value로 새로운 Object를 반환합니다.
The inverse of _.toPairs; this method returns an object composed from key-value pairs.

const fromPairs1 = _.fromPairs([
	["a", 1],
	["b", 2]
]);
// => { 'a': 1, 'b': 2 }

h

_.head(array) < >tail 의 반대 , 비슷한게 initial (마지막 제외)

원본 배열의 첫번째 요소를 반환합니다.
Gets the first element of array.

const head1 = _.head([1, 2, 3]);
// => 1 

const head2 = _.head([]);
// => undefined

i

_.indexOf(array, value, [fromIndex=0]) <> findIndex?>

원본 배열에서 첫번째로 해당하는 요소의 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
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.

const indexOf1 = _.indexOf([1, 2, 1, 2], 2);
// => 1 

// Search from the `fromIndex`.
const indexOf2 = _.indexOf([1, 2, 2, 1], 1, 1);
// => 3

_.initial(array)

원본 배열에서 마지막 요소를 뺀 새로운 배열을 반환합니다.
Gets all but the last element of array.

const initial = _.initial([1, 2, 3, 4, 5]);
// => [1, 2, 3, 4]

_.intersection([arrays]) <> xor() 반대

배열간에 동일한 요소를 새로운 배열로 반환합니다.
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.

const intersection = _.intersection([2, 1, 3], [2, 3, 5]);
// => [2, 3]

_.intersectionBy([arrays], [iteratee=_.identity]) <>xorBy() 반대

배열간에 동일한 요소를 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
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: (value).

const intersectionBy1 = _.intersectionBy(
	[2.1, 1.2],
	[2.3, 3.4],
	Math.floor
);
// => [2.1]

// The `_.property` iteratee shorthand.
const intersectionBy2 = _.intersectionBy(
	[{ x: 1 }],
	[{ x: 2 }, { x: 1 }],
	"x"
);
// => [{ 'x': 1 }]

_.intersectionWith([arrays], [comparator]) <> xorWith() 반대

배열간에 동일한 요소를 새로운 배열로 반환합니다.
✨ 메서드명에 -With가 붙으면 내부 로직을 변경할 수 있습니다.
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).

var objects = [
{ x: 1, y: 2 },
{ x: 2, y: 1 }
];

var others = [
{ x: 1, y: 1 },
{ x: 1, y: 2 }
]; 

const intersectionWith = _.intersectionWith(objects, others, _.isEqual);
// => [{ 'x': 1, 'y': 2 }]

j

_.join(array, [separator=‘,’])

원본 배열의 요소 사이에 separator를 넣어 문자열을 반환합니다.
Converts all elements in array into a string separated by separator.

const join = _.join(["a", "b", "c"], "~");
// => 'a~b~c'

l

_.last(array) <> head와 반대

원본 배열의 마지막 요소를 반환합니다.
Converts all elements in array into a string separated by separator.

const last = _.last([1, 2, 3]);
// => 3

_.lastIndexOf(array, value, [fromIndex=array.length-1])

원본 배열의 마지막 요소를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.indexOf except that it iterates over elements of array from right to left.

const lastIndexOf1 = _.lastIndexOf([1, 2, 1, 2], 2);
// => 3 

// Search from the `fromIndex`.
const lastIndexOf2 = _.lastIndexOf([1, 2, 1, 2], 2, 2);
// => 1

n

_.nth(array, [n=0])

원본 배열의 n번째 요소를 반환합니다. 음수 입력시 뒤에서부터 요소를 반환합니다.
Gets the element at index n of array. If n is negative, the nth element from the end is returned.

var array = ["a", "b", "c", "d"];  

const nth1 = _.nth(array, 1);
// => 'b' 

const nth2 = _.nth(array, -2);
// => 'c'; 

const nth3 = _.nth(array, -4);
// => 'a'; 

const nth4 = _.nth(array, -10);
// => undefined

p

_.pull(array, [values]) <> _.without()와 비슷

원본 배열에 해당하는 요소를 제외하고 원본 배열을 업데이트 합니다.
Removes all given values from array using SameValueZero for equality comparisons.
Note: Unlike _.without, this method mutates array. Use _.remove to remove elements from an array by predicate.

var array = ["a", "b", "c", "a", "b", "c"];  

_.pull(array, "a", "c");
console.log(array);
// => ['b', 'b']

_.pullAll(array, values) <> _.difference()와 비슷

원본 배열에 해당하는 요소를 제외하고 원본 배열을 업데이트 합니다.
This method is like _.pull except that it accepts an array of values to remove.
Note: Unlike _.difference, this method mutates array.

var array = ["a", "b", "c", "a", "b", "c"];  

_.pullAll(array, ["a", "c"]);
console.log(array);
// => ['b', 'b']

_.pullAllBy(array, values, [iteratee=_.identity]) <> differenceBy

원본 배열에 해당하는 요소를 제외하고 원본 배열을 업데이트 합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 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)…
Note: Unlike _.differenceBy, this method mutates array.

var array = [{ x: 1 }, { x: 2 }, { x: 3 }, { x: 1 }]; 

_.pullAllBy(array, [{ x: 1 }, { x: 3 }], "x");
console.log(array);
// => [{ 'x': 2 }]

_.pullAllWith(array, values, [comparator]) <> differenceWith

원본 배열에 해당하는 요소를 제외하고 원본 배열을 업데이트 합니다.
✨ 메서드명에 -With가 붙으면 내부 로직을 변경할 수 있습니다.
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).
Note: Unlike _.differenceWith, this method mutates array.

var array = [
{ x: 1, y: 2 },
{ x: 3, y: 4 },
{ x: 5, y: 6 }
];  

_.pullAllWith(array, [{ x: 3, y: 4 }], _.isEqual);
console.log(array);
// => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }]

_.pullAt(array, [indexes]) <> at()와 비슷

원본 배열에 해당하는 인덱스의 요소를 제외하고 원본 배열을 업데이트 합니다. 그리고 제외된 요소를 새로운 배열로 반환합니다.
Removes elements from array corresponding to indexes and returns an array of removed elements.
Note: Unlike _.at, this method mutates array.

var array = ["a", "b", "c", "d"];
var pulled = _.pullAt(array, [1, 3]); 

console.log(array);
// => ['a', 'c']
console.log(pulled);
// => ['b', 'd']

r

_.remove(array, [predicate=_.identity]) < >filter() 비슷

원본 배열에 해당하는 인덱스의 요소를 제외하고 원본 배열을 업데이트 합니다. 그리고 제외된 요소를 새로운 배열로 반환합니다.
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).
Note: Unlike _.filter, this method mutates array. Use _.pull to pull elements from an array by value.

var array = [1, 2, 3, 4];
var evens = _.remove(array, function (n) {
return n % 2 == 0;
});  

console.log("remove : ", array);
// => [1, 3] 

console.log("remove return: ", evens);
// => [2, 4]

_.reverse(array)

원본 배열을 거꾸로 배치하여 업데이트합니다.
Reverses array so that the first element becomes the last, the second element becomes the second to last, and so on.
Note: This method mutates array and is based on Array#reverse.

var array = [1, 2, 3];
_.reverse(array);
// => [3, 2, 1]

s

_.slice(array, [start=0], [end=array.length])

원본 배열을 잘라 새로운 배열을 반환합니다. ( start <= length < end)
Creates a slice of array from start up to, but not including, end.
Note: This method is used instead of Array#slice to ensure dense arrays are returned.

const arr = [1, 2, 3, 4, 5, 6];
const slice = _.slice(arr, 1, 4);
// [2, 3, 4] 

console.log("arr : ", arr);
// [1, 2, 3, 4, 5, 6]

_.sortedIndex(array, value)

원본 배열의 정렬에 알맞은 위치의 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
Uses a binary search to determine the lowest index at which value should be inserted into array in order to maintain its sort order.

const sortedIndex = _.sortedIndex([30, 50, 80], 60);
// => 1

_.sortedIndexBy(array, value, [iteratee=_.identity])

원본 배열의 정렬에 알맞은 위치의 인덱스를 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
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).

var objects = [{ x: 4 }, { x: 5 }]; 

const sortedIndexBy1 = _.sortedIndexBy(objects, { x: 4 }, function (o) {
	return o.x;
});
// => 0 

// The `_.property` iteratee shorthand.
const sortedIndexBy2 = _.sortedIndexBy(objects, { x: 4 }, "x");
// => 0

_.sortedIndexOf(array, value, [iteratee=_.identity])

정렬된 원본 배열의 정렬에 알맞은 위치의 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.indexOf except that it performs a binary search on a sorted array.

const sortedIndexOf = _.sortedIndexOf([4, 4, 5, 6, 6, 6], 5);
// => 2

_.sortedLastIndex(array, value)

정렬된 원본 배열의 정렬에 알맞은 위치의 마지막 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.indexOf except that it performs a binary search on a sorted array.

const sortedLastIndex = _.sortedLastIndex([4, 5, 5, 5, 6], 5);
// => 4

_.sortedLastIndexBy(array, value, [iteratee=_.identity])

정렬된 원본 배열의 정렬에 알맞은 위치의 마지막 인덱스를 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.sortedLastIndex 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).

var objects = [{ x: 4 }, { x: 5 }]; 

const sortedLastIndexBy1 = _.sortedLastIndexBy(
	objects, { x: 4 },function (o) { return o.x; }
);
// => 1 

// The `_.property` iteratee shorthand.
const sortedLastIndexBy2 = _.sortedLastIndexBy(objects, { x: 4 }, "x");
// => 1

_.sortedLastIndexOf(array, value)

정렬된 원본 배열의 정렬에 알맞은 위치의 마지막 인덱스를 반환합니다.
✨ 메서드명에 -Index가 붙으면 fromIndex를 지정해 요소를 찾기 시작할 인덱스를 정할 수 있습니다.
This method is like _.lastIndexOf except that it performs a binary search on a sorted array.

const sortedLastIndexOf = _.sortedLastIndexOf([4, 5, 5, 5, 6], 5);
// => 3

_.sortedUniq(array)

정렬된 원본 배열의 유니크한 값을 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
This method is like _.uniq except that it’s designed and optimized for sorted arrays.

const sortedUniq = _.sortedUniq([1, 1, 2]);
// => [1, 2]

_.sortedUniqBy(array, [iteratee])

정렬된 원본 배열의 유니크한 값을 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
This method is like _.uniqBy except that it’s designed and optimized for sorted arrays.

const sortedUniqBy = _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor);
// => [1.1, 2.3]

t

_.tail(array) <> initial()

원본 배열에서 첫번째 요소를 뺀 새로운 배열을 반환합니다.
Gets all but the first element of array.

const tail = _.tail([1, 2, 3]);
// => [2, 3]

_.take(array, [n=1]) <> drop() 의 반대

원본 배열을 앞에서부터 n만큼 새로운 배열로 반환합니다.
Creates a slice of array with n elements taken from the beginning.

const take1 = _.take([1, 2, 3]);
// => [1] 

const take2 = _.take([1, 2, 3], 2);
// => [1, 2] 

const take3 = _.take([1, 2, 3], 5);
// => [1, 2, 3]  

const take4 = _.take([1, 2, 3], 0);
// => []

_.takeRight(array, [n=1]) <> dropRight() 의 반대

원본 배열을 뒤에서부터 n만큼 새로운 배열로 반환합니다.
Creates a slice of array with n elements taken from the end.

const takeRight1 = _.takeRight([1, 2, 3]);
// => [1] 

const takeRight2 = _.takeRight([1, 2, 3], 2);
// => [1, 2] 

const takeRight3 = _.takeRight([1, 2, 3], 5);
// => [1, 2, 3]
  
const takeRight4 = _.takeRight([1, 2, 3], 0);
// => []

_.takeRightWhile(array, [predicate=_.identity]) <> dropRightWhile() 의 반대

원본 배열을 뒤에서부터 n만큼 새로운 배열로 반환합니다.
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).

var users = [
{ user: "barney", active: true },
{ user: "fred", active: false },
{ user: "pebbles", active: false }
];  

const takeRightWhile1 = _.takeRightWhile(users, function (o) {
return !o.active;
});
// => objects for ['fred', 'pebbles']  

// The `_.matches` iteratee shorthand.
const takeRightWhile2 = _.takeRightWhile(users, {
user: "pebbles",
active: false
});
// => objects for ['pebbles']  

// The `_.matchesProperty` iteratee shorthand.
const takeRightWhile3 = _.takeRightWhile(users, ["active", false]);
// => objects for ['fred', 'pebbles']  

// The `_.property` iteratee shorthand.
const takeRightWhile4 = _.takeRightWhile(users, "active");
// => []

_.takeWhile(array, [predicate=_.identity]) <> dropWhile() 의 반대

원본 배열을 앞에서부터 n만큼 새로운 배열로 반환합니다.
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).

var users = [
{ user: "barney", active: false },
{ user: "fred", active: false },
{ user: "pebbles", active: true }
];

const takeWhile1 = _.takeWhile(users, function (o) {
return !o.active;
});
// => objects for ['barney', 'fred']  

// The `_.matches` iteratee shorthand.
const takeWhile2 = _.takeWhile(users, { user: "barney", active: false });
// => objects for ['barney']  

// The `_.matchesProperty` iteratee shorthand.
const takeWhile3 = _.takeWhile(users, ["active", false]);
// => objects for ['barney', 'fred']  

// The `_.property` iteratee shorthand.
const takeWhile4 = _.takeWhile(users, "active");
// => []

u

_.union([arrays])

원본 배열들을 합친후 중복을 제거하여 새로운 배열로 반환합니다.
Creates an array of unique values, in order, from all given arrays using SameValueZero for equality comparisons.

const union = _.union([2], [1, 2]);
// => [2, 1]

_.unionBy([arrays], [iteratee=_.identity])

원본 배열들을 합친후 중복을 제거하여 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 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: (value).

const unionBy1 = _.unionBy([2.1], [1.2, 2.3], Math.floor);
// => [2.1, 1.2] 

// The `_.property` iteratee shorthand.
const unionBy2 = _.unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], "x");
// => [{ 'x': 1 }, { 'x': 2 }

_.unionWith([arrays], [comparator])

원본 배열들을 합친후 중복을 제거하여 새로운 배열로 반환합니다.
✨ 메서드명에 -With가 붙으면 내부 로직을 변경할 수 있습니다.
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).

const unionBy1 = _.unionBy([2.1], [1.2, 2.3], Math.floor);
// => [2.1, 1.2] 

// The `_.property` iteratee shorthand.
const unionBy2 = _.unionBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], "x");
// => [{ 'x': 1 }, { 'x': 2 }

_.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.

const uniq = _.uniq([2, 1, 2]);
// => [2, 1]

_.uniqBy(array, [iteratee=_.identity])

원본 배열을 중복을 제거하여 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 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: (value).

const uniqBy1 = _.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]  

// The `_.property` iteratee shorthand.
const uniqBy2 = _.uniqBy([{ x: 1 }, { x: 2 }, { x: 1 }], "x");
// => [{ 'x': 1 }, { 'x': 2 }]

_.unzip(array) <> zip() 반대? 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.

var zipped = _.zip(["a", "b"], [1, 2], [true, false]);
// => [['a', 1, true], ['b', 2, false]] 

const unzip = _.unzip(zipped);
// => [['a', 'b'], [1, 2], [true, false]]

_.unzipWith(array, [iteratee=_.identity])

원본 배열들에서 같은 인덱스에 있는 요소들을 묶어 새로운 배열로 반환합니다.
✨ 메서드명에 -With가 붙으면 내부 로직을 변경할 수 있습니다.
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).

var zipped = _.zip([1, 2], [10, 20], [100, 200]);
// => [[1, 10, 100], [2, 20, 200]]  

const unzipWith = _.unzipWith(zipped, _.add);
// => [3, 30, 300]

w

_.without(array, [values]) <> pull과 비슷

원본 배열에서 해당하는 요소를 제외하고 새로운 배열로 반환합니다.
Creates an array excluding all given values using SameValueZero for equality comparisons.
Note: Unlike _.pull, this method returns a new array.

const without = _.without([2, 1, 2, 3], 1, 2);
// => [3]

x

_.xor([arrays]) <> intersection() 반대

원본 배열들에서 서로 없는 요소들을 새로운 배열로 반환합니다.
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.

const xor = _.xor([2, 1], [2, 3]);
// => [1, 3]

_.xorBy([arrays], [iteratee=_.identity]) <> intersectionBy() 반대

원본 배열들에서 서로 없는 요소들을 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 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).

const xorBy1 = _.xorBy([2.1, 1.2], [2.3, 3.4], Math.floor);
// => [1.2, 3.4]  

// The `_.property` iteratee shorthand.
const xorBy2 = _.xorBy([{ x: 1 }], [{ x: 2 }, { x: 1 }], "x");
// => [{ 'x': 2 }]

_.xorWith([arrays], [comparator]) <> intersectionWith() 반대

원본 배열들에서 서로 없는 요소들을 새로운 배열로 반환합니다.
✨ 메서드명에 -By가 붙으면 배열의 요소를 iteratee로 감쌀 수 있고, Object의 경우 key값으로 할당할 수 있습니다.
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 }
];  

const xorWith = _.xorWith(objects, others, _.isEqual);
// => [{ 'x': 2, 'y': 1 }, { 'x': 1, 'y': 1 }]

z

_.zip([arrays]) <> unzip() 비슷? array로 한번더 감싸져서 리턴됨

원본 배열들에서 같은 인덱스의 요소들을 묶어 새로운 배열로 반환합니다.
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.

const zip = _.zip(["a", "b"], [1, 2], [true, false]);
// => [['a', 1, true], ['b', 2, false]]

_.zipObject([props=[]], [values=[]])

2개의 원본 배열을 key, value쌍으로 새로운 Object를 반환합니다.
This method is like _.fromPairs except that it accepts two arrays, one of property identifiers and one of corresponding values.

const zipObject = _.zipObject(["a", "b"], [1, 2]);
// => { 'a': 1, 'b': 2 }

_.zipObjectDeep([props=[]], [values=[]])

2개의 원본 배열을 key, value쌍으로 새로운 다차원의 Object를 반환합니다.
This method is like _.zipObject except that it supports property paths.

const zipObjectDeep = _.zipObjectDeep(["a.b[0].c", "a.b[1].d"], [1, 2]);
// => { 'a': { 'b': [{ 'c': 1 }, { 'd': 2 }] } }

_.zipWith([arrays], [iteratee=_.identity])

원본 배열들에서 같은 인덱스의 요소들을 묶어 새로운 배열로 반환합니다.
✨ 메서드명에 -With가 붙으면 내부 로직을 변경할 수 있습니다.
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).

const zipObject = _.zipWith([1, 2], [10, 20], [100, 200], 
	function (a,b,c) {
		return a + b + c;
	});
// => [111, 222]

마치며 🍺

Lodash Array 관련 함수들을 알아보았습니다.
하나씩 해보면서 ‘와 이런것도 돼? 오(신기방기)’ 신기하다고 느꼈었고, 또
‘이거는 아까 위에 거랑 같지 않나?’ 차이점이 있나 싶은 것들도 있었습니다.
나중에 시간되면 비슷한 것들을 정리해보는 것도 괜찮을 것 같네요.

우선은 이어서 Lodash Object와 Collection을 정주행하겠습니다.ㅎ

함께하면 좋은 글 😍

728x90