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"]

3
  • Does this answer your question? How to get unique values in an array Commented Dec 3, 2020 at 9:38
  • 1
    What do you mean by object method Commented Dec 3, 2020 at 9:38
  • Are you saying you want to be able to do something like ["A", "B"].removeDupe()? Commented Dec 3, 2020 at 9:40

4 Answers 4

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"]

Sign up to request clarification or add additional context in comments.

2 Comments

may i know any advantages of doing so ? or just to answer OP Q ?
it is fast, because if has O(1) for addressing the object.
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())

Comments

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

Comments

0

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

console.log(removeDuplicates(['Mike', 'Mike', 'Paul']));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.