indexof javascript duplicate arrays 1

indexof javascript duplicate arrays

Array.prototype.getDuplicates = function () {
    var duplicates = {};
    for (var i = 0; i < this.length; i++) {
        if(duplicates.hasOwnProperty(this[i])) {
            duplicates[this[i]].push(i);
        } else if (this.lastIndexOf(this[i]) !== i) {
            duplicates[this[i]] = [i];
        }
    }

    return duplicates;
};

Here is what the above code is Doing:
1. We are adding a new method to the Array prototype called getDuplicates.
2. We are creating an empty object called duplicates.
3. We are looping through the array.
4. If the duplicates object already has a property with the current array value, we are pushing the current index to the array.
5. If the duplicates object does not have a property with the current array value, we are checking if the last index of the current array value is not equal to the current index. If it is not, we are creating a new property with the current array value and setting it to an array with the current index.
6. We are returning the duplicates object.

Now, let's see how we can use this method:

var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
var duplicates = arr.getDuplicates();

console.log(duplicates);

// Output:
// { '1': [ 0, 10 ],
// '2': [ 1, 11 ],
// '3': [ 2, 12 ],
// '4': [ 3, 13 ],
// '5': [ 4, 14 ],
// '6': [ 5, 15 ],
// '7': [ 6, 16 ],
// '8': [ 7, 17 ],
// '9': [ 8, 18 ],
// '10': [ 9, 19 ] }

Similar Posts