여러 중복되는 데이터들을 하나만 남기고 제거하여 고유하게 바꾸어 줍니다.
_.uniq([2, 1, 2]);
// => [2, 1]
기본적으로 .uniq와 같은데, 반복을 판단할 기준점을 정할 수 있습니다.
_.uniqBy([2.1, 1.2, 2.3], Math.floor);
// => [2.1, 1.2]
const usersA = [
{ userId: '1', name: 'HEROPY' },
{ userId: '2', name: 'Neo' }
]
const userB = [
{ userId: '1', name: 'HEROPY' },
{ userId: '3', name: 'Amy'}
]
const usersC = usersA.concat(usersB);
console.log('concat', usersC);
// 0: { userId: '1', name: 'HEROPY' }
// 1: { userId: '2', name: 'Neo' }
// 2: { userId: '1', name: 'HEROPY' }
// 3: { userId: '3', name: 'Amy'}
console.log('uniqBy', _.uniqBy(usersC, 'userId'));
// 0: { userId: '1', name: 'HEROPY' }
// 1: { userId: '2', name: 'Neo' }
// 2: { userId: '3', name: 'Amy'}
중복이 발생할 수 있는 배열 데이터가 2개가 있고 아직 합치기 전이라면
.unionBy()
를 사용하여 고유하게 합칠 수 있습니다.
_.unionBy([2.1], [1.2, 2.3], Math.floor);
// => [2.1, 1.2]
const usersA = [
{ userId: '1', name: 'HEROPY' },
{ userId: '2', name: 'Neo' }
]
const userB = [
{ userId: '1', name: 'HEROPY' },
{ userId: '3', name: 'Amy'}
]
const usersD = _.unionBy(usersA, usersB, 'userId')
console.log('unionBy', usersD);
// 0: { userId: '1', name: 'HEROPY' }
// 1: { userId: '2', name: 'Neo' }
// 2: { userId: '3', name: 'Amy'}
이미 중복이 발생한 배열에 대해서는
.uniqBy()
를 사용하고, 중복이 발생할 수 있는 배열 데이터가 여러개가 있고 아직 합치기 전이라면.unionBy()
를 사용합니다.
배열 데이터에서 찾을 기준에 맞는 데이터를 찾아내서 그 데이터를 반환합니다.
const users = [
{ userId: '1', name: 'HEROPY' },
{ userId: '2', name: 'Neo' },
{ userId: '3', name: 'Amy' },
{ userId: '4', name: 'Evan' },
{ userId: '5', name: 'Lewis' }
]
const foundUser = _.find(users, { name: 'Amy' });
console.log(foundUser);
// { userId: "3", name: "Amy" }
배열 데이터에서 찾을 기준에 맞는 데이터를 찾아내서 그 데이터의 배열index를 반환합니다.
const users = [
{ userId: '1', name: 'HEROPY' },
{ userId: '2', name: 'Neo' },
{ userId: '3', name: 'Amy' },
{ userId: '4', name: 'Evan' },
{ userId: '5', name: 'Lewis' }
]
const foundUserIndex = _.findIndex(users, { name: 'Amy' });
console.log(foundUserIndex);
// 2
배열 데이터에서 찾을 기준에 맞는 데이터를 찾아내서 원본 배열에서 그 데이터를 삭제합니다.
const users = [
{ userId: '1', name: 'HEROPY' },
{ userId: '2', name: 'Neo' },
{ userId: '3', name: 'Amy' },
{ userId: '4', name: 'Evan' },
{ userId: '5', name: 'Lewis' }
]
_.remove(users, { name: 'HEROPY' });
console.log(users);
// 0: { userId: '2', name: 'Neo' },
// 1: { userId: '3', name: 'Amy' },
// 2: { userId: '4', name: 'Evan' },
// 3: { userId: '5', name: 'Lewis' }