0

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,053
  • 2
  • 12
  • 31
fred rondo
  • 15
  • 5
  • Does this answer your question? [How to get unique values in an array](https://stackoverflow.com/questions/11246758/how-to-get-unique-values-in-an-array) – Ivar Dec 03 '20 at 09:38
  • 1
    What do you mean by object method – Joshua Dec 03 '20 at 09:38
  • Are you saying you want to be able to do something like `["A", "B"].removeDupe()`? – DBS Dec 03 '20 at 09:40

4 Answers4

2

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"]
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
0

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())
hgb123
  • 13,869
  • 3
  • 20
  • 38
0

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
0

function removeDuplicates(arr) {
  return Object.keys(
    arr.reduce(
      (val, cur) => ({
        ...val,
        [cur]: true
      }),
      {}
    )
  );
}

console.log(removeDuplicates(['Mike', 'Mike', 'Paul']));
michael
  • 4,053
  • 2
  • 12
  • 31