Skip to content

Instantly share code, notes, and snippets.

@completejavascript
Last active May 15, 2018 03:30
Show Gist options
  • Save completejavascript/6035e2d80bda6c231e6a33d09d725ffc to your computer and use it in GitHub Desktop.
Save completejavascript/6035e2d80bda6c231e6a33d09d725ffc to your computer and use it in GitHub Desktop.
Several methods to deduplicate an array.
let arr = [1, 5, 'a', 3, 'f', '3', 5, 3, 'b', 'e', 'f'];
let ans = deduplicate(arr);
console.log(ans);
// Expected output: [1, 5, "a", 3, "f", "3", "b", "e"]
function deduplicate(arr) {
let isExist = (arr, x) => {
for(let i = 0; i < arr.length; i++) {
if (arr[i] === x) return true;
}
return false;
}
let ans = [];
arr.forEach(element => {
if(!isExist(ans, element)) ans.push(element);
});
return ans;
}
let arr = [1, 5, 'a', 3, 'f', '3', 5, 3, 'b', 'e', 'f'];
let ans = deduplicate(arr);
console.log(ans);
// Expected output: [1, 5, "a", 3, "f", "3", "b", "e"]
function deduplicate(arr) {
return arr.filter((value, index, arr) => arr.indexOf(value) === index);
}
let arr = [1, 5, 'a', 3, 'f', '3', 5, 3, 'b', 'e', 'f'];
let ans = deduplicate(arr);
console.log(ans);
// Expected output: [1, 5, "a", 3, "f", "3", "b", "e"]
function deduplicate(arr) {
let isExist = (arr, x) => arr.includes(x);
let ans = [];
arr.forEach(element => {
if(!isExist(ans, element)) ans.push(element);
});
return ans;
}
let arr = [1, 5, 'a', 3, 'f', '3', 5, 3, 'b', 'e', 'f'];
let ans = deduplicate(arr);
console.log(ans);
// Expected output: [1, 5, "a", 3, "f", "3", "b", "e"]
function deduplicate(arr) {
let isExist = (arr, x) => arr.indexOf(x) > -1;
let ans = [];
arr.forEach(element => {
if(!isExist(ans, element)) ans.push(element);
});
return ans;
}
let arr = [1, 5, 'a', 3, 'f', '3', 5, 3, 'b', 'e', 'f'];
let ans = deduplicate(arr);
console.log(ans);
// Expected output: [1, 5, "a", 3, "f", "3", "b", "e"]
function deduplicate(arr) {
let set = new Set(arr);
return Array.from(set);
}
let arr = [1, 5, 'a', 3, 'f', '3', 5, 3, 'b', 'e', 'f'];
let ans = deduplicate(arr);
console.log(ans);
// Expected output: [1, 5, "a", 3, "f", "3", "b", "e"]
function deduplicate(arr) {
let set = new Set(arr);
return [...set];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment