There are some constraints you should clarify. For example, this code would returns the first number in the array that is duplicated:
let duplicated = [...array] // makes a copy of the array
.sort() // since `sort` mutate the original
.find((item, index, arr) => value === arr[index + 1]);
console.log(duplicated) // 5, in your case
If there is no number duplicated, then it will return undefined
.
However, maybe that is not what you want. Considering this array: [1, 3, 6, 5, 5, 6, 6, 6]
. Even if there is also 6
duplicated, you will always return 5
.
If you want just to know if there is at least a number duplicated, the code above will works. If you want to know all the duplicated number, and in which order they appear first in the original array, you need something different. For example:
let array = [1, 3, 6, 5, 5, 6, 6, 6];
let occurrences = array
.reduce((acc, value) => (acc[value]=-~acc[value], acc),{});
console.log(occurrences); // {"1": 1, "3": 1, "5": 2, "6": 4}
At this point you can decided what do you want to do with this data, e.g. you can filter out the numbers that appears in the array just once:
console.log(
Object.fromEntries(
Object.entries(occurrences).filter(([num, count]) => count > 1)
)
); // {"5": 2, "6": 4}
etc.
UPDATE (see comments):
Object.fromEntries
is a method recently introduced, in case having a filtered object with all the occurrences is the goal, in this context could be easily replaced by a function like this:
const fromEntries = entries =>
entries.reduce((acc, [key, value]) => (acc[key] = value, acc), {});