I've been tackling the issue of removing duplicates from an array, but I've hit a roadblock when it comes to handling NaN values. How can I identify NaN and ensure it's only added once to a new array?
Although my code works flawlessly in most cases, it struggles with NaN values.
removeDupReduce([1, 2, 1, 3, 1, 4]) // This works correctly
removeDupReduce([NaN, 2, NaN, 3, 1, NaN]) // Currently returns ['NaN', 2, 3, 1], but I'm aiming for [NaN, 2, 3, 1]. I know I converted NaN to a string using toString, but I'm open to hearing other suggestions.
function removeDupReduce(list) {
return [...list].reduce((acc, curr) => {
if (acc.indexOf(curr) === -1) {
if (isNaN(curr)) {
curr = curr.toString();
if (acc.indexOf(curr) === -1) {
acc.push(curr);
}
} else {
var a = acc.indexOf(curr);
acc.push(curr);
}
}
return acc;
}, []);
}