From 43aa4bedf66b397dba5ad66cdfa8d4eda2b34e96 Mon Sep 17 00:00:00 2001 From: Tim Marinin Date: Thu, 21 Sep 2017 14:14:25 +0300 Subject: [PATCH] Simplify array_unique Use Array.prototype.indexOf instead of custom key comparator. This change probably makes function slower due to indexOf probable O(n) timing, but clarity of the code is more important than the performance in this case. --- README.md | 23 ++--------------------- 1 file changed, 2 insertions(+), 21 deletions(-) diff --git a/README.md b/README.md index 6c36330..47e2977 100644 --- a/README.md +++ b/README.md @@ -25,30 +25,11 @@ > Remove duplicates from an array ```js function array_unique(arr){ - var seen = {}; var ret_arr = []; - var key; - var i; - - function keyify(obj){ - var ret = ""; - var j; - - if (Object.prototype.toString.call(obj) === "[object Object]" || Object.prototype.toString.call(obj) === "[object Array]"){ - for (j in obj){ - ret += "~" + j + "^" + keyify(obj[j]) + "%"; - } - return ret; - }else{ - return obj; - } - } - for(i = 0; i < arr.length; i++){ - key = keyify(arr[i]); - if(!(key in seen)){ + for (var i = 0; i < arr.length; i++){ + if (ret_arr.indexOf(arr[i]) === -1){ ret_arr.push(arr[i]); - seen[key] = true; } }