How to use the uniq function from underscore

Find comprehensive JavaScript underscore.uniq code examples handpicked from public code repositorys.

underscore.uniq is a function that removes duplicate values from an array and returns a new array.

1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112


// selectors [...group1, ...group2]
const createGroupFileSelectors = (rs, { base, name1, name2 }) => {
  const selectors1 = require(`${relativePath(name1)}/selectors.json`);
  const selectors2 = require(`${relativePath(name2)}/selectors.json`);
  const selectors = uniq([...selectors1, ...selectors2]);


  rs.push(
    new Vinyl({
      path: `${base}/selectors.json`,
fork icon76
star icon255
watch icon0

+ 2 other calls in file

172
173
174
175
176
177
178
179
180
181
            usernames.push(filename.replace(USER_CACHE_PREFIX, "")); // If you are an admin, add all of the usernames from this domain to the variable
         }
      }
   });
}
usernames = _.uniq(usernames); // Makes the list unique (admins will have themselves twice) 
// Eventually should just remove all admins here!
for (var username in usernames) { // Usernames is now a list of all users or just the single loggeed in user.
   var user_config_path = path.join(master_path, USER_CACHE_PREFIX + usernames[username]);
   if (!utils.directoryExists(user_config_path)) {
fork icon29
star icon68
watch icon15

How does underscore.uniq work?

underscore.uniq works by iterating over the elements of the input array and adding each unique element to a new array. It uses a hash table to keep track of the unique elements that have already been encountered and skips over any duplicates. The resulting new array contains only the unique elements of the original array, in the order in which they first appeared. Here is a simplified version of how underscore.uniq works: Create an empty hash table to keep track of unique values. Create an empty result array. Iterate over the elements of the input array. For each element, check if it is already in the hash table. If it is not in the hash table, add it to the hash table and to the result array. If it is in the hash table, skip it. Return the result array containing only the unique elements of the input array. underscore.uniq also has an optional boolean parameter isSorted, which can be set to true to indicate that the input array is already sorted. In this case, underscore.uniq can use a more efficient algorithm that does not require the hash table. Instead, it simply checks adjacent elements of the sorted array and removes any duplicates.

876
877
878
879
880
881
882
883
884
885
            targets = targets.concat(event.context.event.card);
        } else if (event.card) {
            targets = targets.concat(event.card);
        }

        map.set(src, _.uniq(targets));
    }
}

return [...map.entries()].map(([source, targets]) => ({
fork icon9
star icon10
watch icon1

2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
};

// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
  return _.uniq(_.flatten(arguments, true));
};

// Produce an array that contains every item shared between all the
// passed-in arrays.
fork icon0
star icon2
watch icon0

Ai Example

1
2
3
4
5
6
const _ = require("underscore");

const arr = [1, 2, 2, 3, 4, 4, 5];
const uniqArr = _.uniq(arr);

console.log(uniqArr); // Output: [1, 2, 3, 4, 5]

In this example, we first import the underscore library using require(). We then create an array arr that contains some duplicate elements. We pass arr to _.uniq() to remove the duplicates and assign the result to uniqArr. Finally, we log the contents of uniqArr to the console, which contains only the unique elements of arr.

2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236


function formFamilyDataWithRawData(familyDataArray)
{
    return new Promise((resolve,reject)=>{
        let familyList = [];
        let familyIds = _.uniq(_.pluck(familyDataArray,'familyId'));
        familyIds.forEach(familyId => {
            let familyObj = _.reject(familyDataArray,(element)=>{
                return element.familyId != familyId
            })
fork icon0
star icon0
watch icon1

+ 35 other calls in file

8835
8836
8837
8838
8839
8840
8841
8842
8843
8844
};

// Produce an array that contains the union: each distinct element from all of
// the passed-in arrays.
_.union = function() {
  return _.uniq(concat.apply(ArrayProto, arguments));
};

// Produce an array that contains every item shared between all the
// passed-in arrays.
fork icon0
star icon0
watch icon1

+ 2 other calls in file

282
283
284
285
286
287
288
289
290

const topVolTo2Week = sortAndCut(fixed, 'computed.projectedVolumeTo2WeekAvg', count / 3);
// const topDollarVolume = sortAndCut(fixed, 'computed.dollarVolume', 30, COUNT / 3);
const topVolTickers = sortAndCut(fixed, 'computed.projectedVolume', count);

const volumeTickers = uniq([
  ...topVolTo2Week,
  ...topVolTickers,
], 'ticker');
fork icon0
star icon0
watch icon1

+ 5 other calls in file

256
257
258
259
260
261
262
263
264
265
    }
});
return {
    offset: offsetKey,
    score: max,
    tickers: uniq(
        tickers.sort((a, b) => b.zScoreSum - a.zScoreSum),
        'ticker'
    )
};
fork icon0
star icon0
watch icon1

+ 23 other calls in file

447
448
449
450
451
452
453
454
455
456
        ],
        fields: ['company_id']
    });
    company_ids = _.pluck(orgs, 'company_id');
    // company_ids中的空值就空着,不需要转换成根组织ID值
    company_ids = _.uniq(_.compact(company_ids));
    await suObj.directUpdate(_id, {
        company_ids: company_ids
    });
}
fork icon0
star icon0
watch icon1

194
195
196
197
198
199
200
201
202
203
  if (err != null) {
    logger.debug({ err }, 'error checking for updates')
    finish()
    return
  }
  pending = _.uniq(results, false, result => result.doc_id.toString())
  TOTAL = pending.length
  logger.debug(`found ${TOTAL} documents to archive`)
  return processUpdates(pending)
})
fork icon0
star icon0
watch icon202

+ 5 other calls in file

2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
      Price[i].discountedExpMessage = discountedExpMessage;
    }
  }
  const vat = await services.MongoService.getFirstMatch('AdminSetting', {}, { vatPercentage: 1, _id: 0 }, { lean: true });
  const data = {
    Price: _.uniq(Price, price => price.productName),
    vat,
  };
  return universalFunctions.sendSuccess(headers, data); // return MAKE if nothing present
} catch (error) {
fork icon0
star icon0
watch icon1

+ 3 other calls in file

35
36
37
38
39
40
41
42
43
44
const agenda = new Agenda(connectionOptions);

async function isDuplicateServiceID(payloadData) {
  try {
    const serviceLength = payloadData.serviceID.length;
    const uniqueServices = _.uniq(payloadData.serviceID);
    if (uniqueServices.length !== serviceLength) {
      return true;
    }
    return false;
fork icon0
star icon0
watch icon1

+ 3 other calls in file

152
153
154
155
156
157
158
159
160
161
    ...highVolCheapy,
    ...lowRSI,
    // ...Object.values(collectionScans).flat()
].flat();

const novemberOversoldRunScanPicks = uniq(
    everything
        .filter(pick => {
            const rsiOversold = getRSI(pick) < 30;
            const highZScore = pick.zScoreSum > 170;
fork icon0
star icon0
watch icon0

212
213
214
215
216
217
218
219
  if (_.isEmpty(unibuild.pkg.plugins))
    return;
  activePluginPackages.push(unibuild.pkg);
});

activePluginPackages = _.uniq(activePluginPackages);

// *** Assemble the list of source file handlers from the plugins
fork icon0
star icon0
watch icon2

75
76
77
78
79
80
81
82
83
  var assignedVariables = [];
  _.each(self.files, function (file) {
    assignedVariables = assignedVariables.concat(
      file.computeAssignedVariables());
  });
  assignedVariables = _.uniq(assignedVariables);

  return _.isEmpty(assignedVariables) ? undefined : assignedVariables;
},
fork icon0
star icon0
watch icon2

+ 5 other calls in file