10 examples of 'js array unique' in JavaScript

Every line of 'js array unique' 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
33function unique (array) {
34 var res = []
35
36 for(var i = 0,iL = array.length;i < iL;i++) {
37 var current = array[i]
38 if(res.indexOf(current) === -1) {
39 res.push(current)
40 }
41 }
42
43 return res
44}
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

23function unique(array){
24 var o = {};
25 for(var i=0; i<array.length; i++){
26 var item = array[i];
27 //判断字典中是否已经存在该值
28 //如果不存在 = 1
29 //如果存在 + 1
30 if(o[item]){
31 o[item]++;
32 }else{
33 o[item] = 1;
34 }
35 }
36 // 删掉原来的数组
37 array = null;
38 // 去重后的新数组
39 var newArray = [];
40 for(var key in o) {
41 newArray.push(key);
42 }
43 return newArray;
44}
228export function arrayUnique(array) {
229 let unique = [];
230
231 arrayEach(array, (value) => {
232 if (unique.indexOf(value) === -1) {
233 unique.push(value);
234 }
235 });
236
237 return unique;
238}
19function unique(array) {
20 var n = -1;
21
22 while (++n < array.length) {
23 remove(array, array[n], n);
24 }
25
26 return array;
27}
104function arrayUniqueTest() {
105 // var target = [1, 2, 3, 3, '3', '3', 'length', '__proto__', 'prototype', true, false, true, {}, {}, null, null];
106 var target = [1, 2, 3, 3, '3', '3', '__proto__', '__proto__', '__proto__', 'prototype', 'prototype', true, false, true, {}, {}, null, null];
107 // var target = [1, '1', true, 'true'];
108 console.log('\narrayUnique test:\n', arrayUnique(target));
109}
927function unique2(array){
928 var n = {}, r = [], len = array.length, val, type;
929 for (var i = 0; i < array.length; i++) {
930 val = array[i];
931 type = typeof val;
932 if (!n[val]) {
933 n[val] = [type];
934 r.push(val);
935 } else if (n[val].indexOf(type) < 0) {
936 n[val].push(type);
937 r.push(val);
938 }
939 }
940 return r;
941}
77function unique(array) {
78 return array.filter(function (item, idx) {
79 return array.indexOf(item) === idx;
80 });
81}
53function unique2(array){
54 var res = [];
55
56 for(var i =0; i<array.length;i++){
57 var item = array[i];
58 for(var j= 0; j < res.length; j++){
59 if(res[j] === item){
60 break;
61 }
62 }
63 if(j === res.length){
64 res.push(item);
65 }
66 }
67 return res;
68}
392function unique(arr) {
393 return removeDuplicates(arr);
394}
39function unique2 (array) {
40 var res = []
41 var sortedArray = array.concat().sort()
42 var seen
43 for (var i = 0, len = sortedArray.length; i < len; i++) {
44 // 如果是第一个元素或者相邻的元素不相同
45 if (!i || seen !== sortedArray[i]) {
46 res.push(sortedArray[i])
47 }
48 seen = sortedArray[i]
49 }
50 return res
51}

Related snippets