JavaScript Program:
function removeDuplicate(arr) {
return [...new Set(arr.filter(item => typeof item === 'number'))];
}
const result = removeDuplicate([1, 2, 3, 4, 5, 2, 3, 6, 7, 3, "1", "2", "3"]);
console.log(result);
Here’s a breakdown of the code:
function removeDuplicate(arr) {
return [...new Set(arr.filter(item => typeof item === 'number'))];
}
Function Declaration:
function removeDuplicate(arr) { ... }: This declares a function named removeDuplicate that takes one parameter arr, which is expected to be an array.
Filtering:
arr.filter(item => typeof item === 'number'): This line creates a new array that includes only the elements from arr that are of type number. The filter method goes through each item in the array and checks its type using typeof. Only numeric items are kept.
Removing Duplicates:
new Set(...): This creates a new Set object from the filtered array. A Set is a built-in JavaScript object that stores unique values, so any duplicates in the filtered array are automatically removed.
Spread Operator:
[...new Set(...)]: The spread operator (...) is used to convert the Set back into an array. This is necessary because Set objects do not have array methods.
Return Statement:
The function returns the new array containing unique numeric values.
const result = removeDuplicate([1, 2, 3, 4, 5, 2, 3, 6, 7, 3, "1", "2", "3"]);
Function Call:
This line calls the removeDuplicate function with an array that includes both numbers and strings. The result of this call is stored in the variable result.
console.log(result);
Output:
Finally, this line prints the result to the console, which will show the unique numeric values from the original array.
Overall, this code effectively filters out non-numeric values and removes duplicates from an array of mixed types.
No comments:
Post a Comment