How to use the uniqBy function from lodash

Find comprehensive JavaScript lodash.uniqBy code examples handpicked from public code repositorys.

lodash.uniqBy is a function in the Lodash library that creates a new array containing only unique elements by using a provided iteratee function to compare values.

412
413
414
415
416
417
418
419
420
421
module.exports.unescape            = _.unescape;
module.exports.union               = _.union;
module.exports.unionBy             = _.unionBy;
module.exports.unionWith           = _.unionWith;
module.exports.uniq                = _.uniq;
module.exports.uniqBy              = _.uniqBy;
module.exports.uniqWith            = _.uniqWith;
module.exports.uniqueId            = _.uniqueId;
module.exports.unset               = _.unset;
module.exports.unsplat             = _.unsplat;
fork icon19
star icon122
watch icon0

+ 92 other calls in file

2100
2101
2102
2103
2104
2105
2106
2107
2108
2109

if (this.isMultiSelect) {
  var selectedOptionIds = selectedOption.map(function (_selectedOption) {
    return _selectedOption.key;
  }),
      optionsToSearch = lodash.uniqBy([].concat(_toConsumableArray(this.injected.value), _toConsumableArray(this.options)), 'id'),
      foundOptions = optionsToSearch.filter(function (option) {
    return selectedOptionIds.includes(option.id);
  });
  onChange(mobx.toJS(foundOptions));
fork icon3
star icon15
watch icon0

How does lodash.uniqBy work?

lodash.uniqBy is a utility function in the Lodash library that returns a new array with unique values, based on a property of each element specified by an iteratee function. If multiple elements have the same value returned by the iteratee function, only the first one encountered is kept. The original array is not modified.

120
121
122
123
124
125
126
127
128
129
const { negeri } = req.query;
const all = await Superadmin.find({
  negeri: Dictionary[negeri],
  accountType: 'daerahSuperadmin',
});
const specDaerah = _.uniqBy(all, 'daerah');
let daerah = [];
specDaerah.forEach((item) => {
  let daerahDetails = {};
  if (item.daerah !== '-') {
fork icon1
star icon4
watch icon0

+ 11 other calls in file

162
163
164
165
166
167
168
169
170
171
172
173
174
console.log(unionWith); // => [2.1, 1.2]


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


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


const uniqWith = _.uniqWith([2.1, 1.2, 2.3], (a, b) => Math.floor(a) === Math.floor(b));
console.log(uniqWith); // => [2.1, 1.2]
fork icon0
star icon4
watch icon0

+ 15 other calls in file

Ai Example

1
2
3
4
5
6
7
8
9
const arr = [
  { id: 1, name: "Alice" },
  { id: 2, name: "Bob" },
  { id: 1, name: "Charlie" },
];
const uniqueArr = _.uniqBy(arr, "id");

console.log(uniqueArr);
// Output: [{ id: 1, name: 'Alice' }, { id: 2, name: 'Bob' }]

In this example, lodash.uniqBy is used to remove duplicate objects from the arr array based on their id property. The resulting array uniqueArr contains only the first occurrences of the objects with unique id values.

711
712
713
714
715
716
717
718
719
720
721
722


// Unique events with last updated status
function getUniqueStacksEvents(events) {
  // sort in reverse chronological order
  const sortedEvents = [...events].sort((a, b) => b.TimeStamp - a.TimeStamp);
  return _.uniqBy(sortedEvents, 'PhysicalResourceId');
}


function filterNestedStacks(uniqueEvents, excludeWithStatus = CFN_SUCCESS_STATUS, includeWithStatus = []) {
  const nestedStacks = [];
fork icon754
star icon0
watch icon147

+ 4 other calls in file

940
941
942
943
944
945
946
947
948
949
950
951
      Boom.badRequest(
        i18n.translateError('DNS_CHANGES_TAKE_TIME', domain.locale)
      )
    );


  return { ns, txt, mx, errors: _.uniqBy(errors, 'message') };
}


Domains.statics.getVerificationResults = getVerificationResults;

fork icon66
star icon526
watch icon8

11
12
13
14
15
16
17
18
19
20
21
22
23
24


const cwd = process.cwd();


const unl = (val, otherwise) => ((val !== undefined) ? val : otherwise);


const clearDuplicated = files => _.uniqBy(files, f => path.parse(f.path).base);


const filesToIgnore = [
  '.DS_Store',
  'Thumbs.db',
fork icon44
star icon194
watch icon3

23
24
25
26
27
28
29
30
31
32
33
		});


		if (!data[parsed.word]) {
			data[parsed.word] = cleaned;
		} else if (data[parsed.word] && Array.isArray(data[parsed.word])) {
			data[parsed.word] = _.uniqBy(data[parsed.word].concat(cleaned));
		}
	}
});

fork icon7
star icon11
watch icon12

159
160
161
162
163
164
165
166
167
168
createPage({
  path: `/categorie/${collection.slug}`,
  component: './src/templates/Collection.vue',
  context: {
    global,
    products: _.uniqBy(products, 'slug'),
    collection,
    parentCollection: parent,
    siblingCollections: siblings,
    childCollections: children,
fork icon3
star icon9
watch icon1

+ 2 other calls in file

747
748
749
750
751
752
753
754
755
756
async writeVideosIntoFile(file, logger, prefix, courses, filename) {
    if (!file) {
        logger.info(`${prefix} - Starting writing to a file ...`)
        //await fs.writeFile(`./json/${filename}`, JSON.stringify(courses, null, 2), 'utf8');
        courses = orderBy(courses, [o => Number(o.downPath.split('-')[0]), 'position'], ['asc', 'asc']);
        courses = uniqBy(courses, 'url');
        await fs.ensureDir(path.resolve(__dirname, '../json'))
        await fs.writeFile(path.resolve(__dirname, `../json/${filename}`), JSON.stringify(courses, null, 2), 'utf8')
        logger.info(`${prefix} - Ended writing to a file ...`)
        // return Promise.resolve()
fork icon0
star icon4
watch icon1

+ 2 other calls in file

37
38
39
40
41
42
43
44
45
46
case "gameStateChanged":
case "matchStateEnd":
    data.state = line.state;
    if (data.state === "PickLoadout") {
        //determine # of starting teams
        let count = _.uniqBy(Object.values(data.players), "teamId").length;
        console.log(count);
        data.totalTeams = count;
        data.teamsAlive = count;
    }
fork icon3
star icon1
watch icon2

29
30
31
32
33
34
35
36
37
38
    ]
    : [];
return _([...this.dataMap.values()])
    .groupBy('originalPath')
    .flatMap((instances, group) => {
    const locations = _.uniqBy(instances, 'location');
    // #331 - When multiple locations are involved, all of them must pass the validation.
    // If none of the locations contain the field, we at least include one for error reporting.
    // #458, #531 - Wildcards are an exception though: they may yield 0..* instances with different
    // paths, so we may want to skip this filtering.
fork icon0
star icon0
watch icon2

376
377
378
379
380
381
382
383
384
385
386
387
388


	})


	return {
	  labelRecords: flattenDeep(rows.map( r => r.labelRecords)),
	  formRecords: uniqBy(flattenDeep(rows.map( r => r.formRecords)), f => f.id)
	}


}

fork icon0
star icon0
watch icon1

+ 2 other calls in file

195
196
197
198
199
200
201
202
203
204
//         })
//     })
// })
// console.log('1series', specialCourses.length);
series = [...series, ...specialCourses]
// series = uniqBy(series, 'url');
// console.log('2series', series.length);
return all ? series : ([series.find(({ url }) => link.includes(url)) ?? link])
/*const link = links.find(link => url.includes(link.txt))
if (!link) {
fork icon0
star icon0
watch icon1

96
97
98
99
100
101
102
103
104
105
106
  const userTz = user.tz_info.timezone;
  const pickedUser = {
    ..._.pick(user, ["id", "email", "full_name", "image_id"]),
    timezone: userTz,
  };
  const users = _.uniqBy([...collaborators, pickedUser], "id");
  return { data: users, sync_token: null, full_sync: null };
};


module.exports.validate = async (account) => {
fork icon0
star icon0
watch icon1

+ 2 other calls in file

112
113
114
115
116
117
118
119
120
121
122
123
function uniqCaseInsensitive (array, trim = true) {
  if (trim) {
    array = array.map(item => String(item).trim())
  }


  return _.uniqBy(array, item => String(item).toLowerCase())
}


module.exports = {
  epochToDate,
fork icon0
star icon0
watch icon1

+ 2 other calls in file

1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
const res = await Promise.all(promises);
let aggregatedRes = [];
_.forEach(res, (response) => {
  _.forEach(response.rows, row => aggregatedRes.push(row));
})
aggregatedRes = _.uniqBy(aggregatedRes, 'dataValues.program_id');
loggerService.exitLog({responseCode: 'OK'}, logObject);
return response.status(200).send(successResponse({
  apiId: 'api.program.list',
  ver: '1.0',
fork icon0
star icon0
watch icon1

+ 3 other calls in file

1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
  const res = await this.getContribUserPrograms(data, filters);
  let aggregatedRes = [];
  _.forEach(res, (response) => {
    _.forEach(response.rows, row => aggregatedRes.push(row));
  })
  return _.uniqBy(aggregatedRes, 'dataValues.program_id');
}
else if(organisation_id || user_id) {
  let prg_list;
  if (_.get(organisation_id, 'ne') || _.get(user_id, 'ne')) {
fork icon0
star icon0
watch icon1

93
94
95
96
97
98
99
100
101
102
const mapRetails = []
for (let i = 0; i < retails.length; i++) {
  let retail = retails[i];
  const traders1 = _.filter(contractlist, (item) => item.ret_code === retail.ret_code)
  const traders2 = _.filter(pricelist, (item) => item.ret_code === retail.ret_code)
  const traders = _.uniqBy(traders1.concat(traders2), 'trd_code')

  // ลบ field ที่มีค่า null ออก
  retail = _.pickBy(retail, (v) => v !== null && v !== undefined && v !== '')
  // ลบ field ที่ไม่ต้องการนำเข้าข้อมูลออก
fork icon0
star icon0
watch icon1

317
318
319
320
321
322
323
324
325
326
let plans = await TbPL.getPcPlanList3(req.body.ship_date, prdGradeId, truckplantids, plId)
plans = _.orderBy(plans, ["plant_id", "prd_grade_qty"], ["asc", "desc"])

plans = _.filter(plans, (pcplan) => checkPcPlanBalance(pcplan))
pcplans = await getSlottimeToPcPlan(pcplans, plans, req.body.ship_date, hprdgrade)
pcplans = _.uniqBy(pcplans, 'plant_id')

// ถ้ามีมากกว่า 1 โรง ให้สลับกับโรงก่อนหน้า
if (pcplans.length > 1) {
  lastpl = await TbPL.find()
fork icon0
star icon0
watch icon1

+ 2 other calls in file

Other functions in lodash

Sorted by popularity

function icon

lodash.get is the most popular function in lodash (7670 examples)