简体   繁体   中英

Remove duplicates in the array using an object method

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

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

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())

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM