I need to speed this up to pass a code fights test (javascript)

Viewed 310

The task was to take an array and return the earliest duplicate, and if there are none return -1. I wrote it like this:

function firstDuplicate(a) {
    let singles = [];

    for (let i = 0; i < a.length; i++) {

        if (singles.indexOf(a[i]) == -1) {
            singles.push(a[i]);
        }
        else {
            return a[i];
        }

    }

    return -1;
}

It passed all tests except the hidden speed test. Is there another way to write this faster in JS? I saw a Java solution that used sets instead of arrays but I wanted to stick with JS.

3 Answers
Related