I'm curious how you'd be able to do this by utilizing an object method. Is it possible?
function removeDuplicates(arr) {
var result = [];
for (var i = 0; i < arr.length; i++) {
if (result.indexOf(arr[i]) === -1) {
result.push(arr[i]);
}
}
return result;
}
console.log(removeDuplicates(['Mike', 'Mike', 'Paul'])); // returns ["Mike", "Paul"]
michael
4,1733 gold badges15 silver badges31 bronze badges
4 Answers 4
You could take an object and return only the keys.
function removeDuplicates(arr) {
const seen = {};
for (let i = 0; i < arr.length; i++) seen[arr[i]] = true;
return Object.keys(seen);
}
console.log(removeDuplicates(["Mike", "Mike", "Paul"])); // ["Mike", "Paul"]
answered Dec 3, 2020 at 9:39
Nina Scholz
388k26 gold badges367 silver badges417 bronze badges
Sign up to request clarification or add additional context in comments.
2 Comments
KcH
may i know any advantages of doing so ? or just to answer OP Q ?
Nina Scholz
it is fast, because if has O(1) for addressing the object.
Yes, you could use built-in Set()
const data = ["Mike", "Mike", "Paul"]
const res = Array.from(new Set(data))
console.log(res)
You could utilize by making it a method of the array
Array.prototype.removeDuplicates = function() {
return Array.from(new Set(this))
}
const data = ["Mike", "Mike", "Paul"]
console.log(data.removeDuplicates())
answered Dec 3, 2020 at 9:38
hgb123
14.9k3 gold badges24 silver badges43 bronze badges
Comments
If i understood correctly, you could extend the Array object with a removeDuplicates() method, just like this:
if (!Array.prototype.removeDuplicates) { // Check if the Array object already has a removeDuplicates() method
Array.prototype.removeDuplicates = function() {
let result = [];
for(var i = 0; i < this.length; i++){
if(result.indexOf(this[i]) === -1) {
result.push(this[i]);
}
}
return result;
}
}
const arr = ["Mike", "Mike", "Paul"];
console.log(arr.removeDuplicates()); // Call the new added method
answered Dec 3, 2020 at 9:42
Eyad Bereh
1,8781 gold badge16 silver badges38 bronze badges
Comments
function removeDuplicates(arr) {
return Object.keys(
arr.reduce(
(val, cur) => ({
...val,
[cur]: true
}),
{}
)
);
}
console.log(removeDuplicates(['Mike', 'Mike', 'Paul']));
answered Dec 3, 2020 at 9:43
michael
4,1733 gold badges15 silver badges31 bronze badges
Comments
lang-js
["A", "B"].removeDupe()?