10 examples of 'how to find duplicate values in array using javascript' in JavaScript

Every line of 'how to find duplicate values in array using javascript' code snippets is scanned for vulnerabilities by our powerful machine learning engine that combs millions of open source libraries, ensuring your JavaScript code is secure.

All examples are scanned by Snyk Code

By copying the Snyk Code Snippets you agree to
this disclaimer
270export function getDuplicateNames(indexableArray: { name: string }[]): string[] {
271 const seen: { [name: string]: number } = {};
272 const duplicates: string[] = [];
273
274 indexableArray.forEach((element: { name: string }) => {
275 const { name } = element;
276 const count = seen[name] || 0;
277
278 if (count === 1) {
279 duplicates.push(name);
280 }
281 seen[name] = count + 1;
282 });
283 return duplicates;
284}
Important

Use secure code every time

Secure your code as it's written. Use Snyk Code to scan source code in minutes – no build needed – and fix issues immediately. Enable Snyk Code

52function horribleDuplicates (array) {
53 for (var i = 0; i < array.length; i++) {
54 for (var j = 0; j < array.length; j++) {
55 if (array[i] == array[j]) {
56 return true
57 }
58 }
59 }
60 return false
61}
30function duplicateArray(arr) {
31 var newArr = [];
32 for(var i=0, arrSize=arr.length; i<arrSize; i++) {
33 newArr.push(arr[i]);
34 }
35 return newArr;
36}
64function duplicateArray(array) {
65 return array.clone ? array.clone() : new Array(array.length);
66}
53function testForDuplicates(obj, key, dups) {
54 test(wrap(key) + ' has no duplicate', function() {
55 var id = key.toUpperCase(),
56 exists = id in dups;
57
58 if (exists) {
59 dups[id].push(key);
60 } else {
61 dups[id] = [ key ];
62 }
63
64 assert.ok(!exists, dups[id].join(', '));
65 });
66}
25function removeDuplicates_for_loop(arr) {
26 let res = [];
27 const len = arr.length;
28 for (let i = 0; i < len; i++) {
29 if (res.indexOf(arr[i]) === -1) {
30 res.push(arr[i]);
31 }
32 }
33 return res;
34}
79export function uniqueValues<T>(array: T[]): T[] {
80 return Array.from(new Set(array));
81}
12function uniqueAdd(obj, key, values) {
13 const a = (obj[key] = obj[key] || []);
14
15 for (let i = 0; i < values.length; i++) {
16 if (a.indexOf(values[i]) === -1) {
17 a.push(values[i]);
18 }
19 }
20}
48function removeDuplicates(_array) {
49 var _uniques = [], _dupl = [], i = 0;
50 for (i; i <= _array.length; i++) {
51 var v = _array[i];
52 console.log(i + '-' + v);
53 if (_array.lastIndexOf(v) > i || _dupl.indexOf(v) > -1) {
54 _dupl.push(v);
55 } else {
56 _uniques[_uniques.length] = v;
57 }
58 }
59
60 return $.grep(_uniques, function(n, i) {
61 return (n);
62 });
63}
18function unique<T>(array: T[]): T[] {
19 const map: {
20 [key: string]: T;
21 } = {};
22 array.forEach(i => {
23 const key = String(i);
24 if (map[key]) return;
25 map[key] = i;
26 });
27 return Object.keys(map).map(key => map[key]);
28}

Related snippets