Identify duplicate elements in an array.
Cerosh Jacob
Software Engineering Manager @ Commonwealth Bank | Automation testing, technology innovation
This function takes an array of numbers to create a new Set object. If an element is a duplicate, it will not be included in the Set object and will return?false. This value is then negated to?true, which allows the element to be added to the result array, which is ultimately returned.
The?.filter?method iterates over each array element, executing a provided callback function. This function determines whether an element should be included in the resultant filtered array. If the callback function returns?true?for an element, that element is included in the new array. The callback function, defining the filtering criteria, takes two arguments:?element?(the current element being processed), and?index?(the index of the current element in the array). If not needed, the?index?argument can be omitted. Importantly,?.filter?does not modify the original array, but creates a new one with the filtered elements.
A Set stores?unique values?and does not allow duplicate entries. It can contain elements of any data type, including numbers, strings, and objects. Sets maintain the insertion order, meaning the order in which elements are added is preserved when iterating through the Set. However, this order may not be consistent across different executions of your program.
领英推荐
function findDuplicateElementInArray(numberArray: Array<number>): Array<number>{
const setArray = new Set(numberArray);
return numberArray.filter((item) => {
return !(setArray.delete(item))
})
}
const number_array = [5, 3, 8, 5]
console.log(findDuplicateElementInArray(number_array))