Locate any instances of NaN and include them in the updated array

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;
    }, []);
}

Answer №1

To locate NaN in an array, you can utilize the array.findIndex method as demonstrated below:

function eliminateDuplicates(arr) {
    return [...arr].reduce((acc, current) => {

        if (acc.indexOf(current) === -1) {
            if (isNaN(current)) {
                if (acc.findIndex(Number.isNaN) === -1) {
                    acc.push(current);
                }
            } else {
                var index = acc.indexOf(current);
                acc.push(current);
            }
        }
        return acc;
    }, []);
}
console.log("eliminateDuplicates([1, 2, 1, 3, 1, 4])");
console.log(eliminateDuplicates([1, 2, 1, 3, 1, 4]));
console.log("eliminateDuplicates([NaN, 2, NaN, 3, 1, NaN])");
console.log(eliminateDuplicates([NaN, 2, NaN, 3, 1, NaN]));

Answer №2

To identify NaN values, you can utilize either acc.find(a => a !== a) or acc.find(a => isNaN(a)), as both methods are effective.

removeDuplicateElements([1, 2, 1, 3, 1, 4]) // Working as expected
removeDuplicateElements([NaN, 2, NaN, 3, 1, NaN]) // The current output is ['NaN', 2, 3, 1], but I desire it to be [NaN, 2, 3, 1]. I am aware that I unintentionally converted them to strings using toString, so I'm open to alternative suggestions.

function removeDuplicateElements(list) {
    return [...list].reduce((acc,curr)=>{

        if(acc.indexOf(curr) === -1){
            if(isNaN(curr)){
                if(acc.find(a => a !== a))
                acc.push(curr)
            }
            else{
            var a = acc.indexOf(curr)
            acc.push(curr)
            }
        }
        return acc
    },[])
}

Answer №3

NaN is actually not equal to NaN. This fact may seem strange, but it is what it is.

indexOf method will compare items one by one to check if they are equal to your value. However, since NaN != NaN, it will always result in -1.

You can test this by running:

[NaN].indexOf(NaN) // this will give you -1

If you want to determine if an array contains NaN, you should use the find method along with isNaN.

if (acc.find(item => isNaN(item)) // this means we have NaN in the array.

Make sure to update your if statement accordingly:

if(acc.indexOf(curr) === -1 && (!isNaN(curr) || !acc.find(item => isNaN(item))) {
 acc.push(curr)
}

Answer №4

The reason for the error is that your if statement is not accurate. You should verify whether Boolean(curr) is true because Boolean(NaN) will return false. When you simply mention the variable curr within the condition, it automatically converts to Boolean(curr) and evaluates as either true or false. Additionally, you have a redundant condition in your code with acc.indexOf(). I recommend trying out my solution:

console.log(removeDupReduce([1, 2, 1, 3, 1, 4]))
console.log(removeDupReduce([NaN, 2, NaN, 3, 1, NaN]))
function removeDupReduce(list) {
    return [...list].reduce((acc,curr)=> curr && acc.indexOf(curr) === -1 ? [...acc, curr] : acc, [])
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Different approach for binding in Vue.js

Seeking Alternatives I am curious to find out if Vue.js offers a different approach for outputting data beyond the conventional curly braces. Is there a syntax similar to Angular's ng-bind directive that I could utilize? Although Vue.js primarily ut ...

Struggling with running a jQuery ajax request inside a function?

Below is my code for a jQuery Change Event: $("input[name=evnt_typ]").change(function(){ var request = $.ajax({ method: "POST", url: "ajaxRequest.php", dataType: "json ...

Laravel triggers a 'required' error message when all fields have been filled

As I attempt to submit a form using an axios post request in laravel, I encounter an issue with the validation of the name and age fields, along with an image file upload. Here is a breakdown of the form structure: Below is the form setup: <form actio ...

Converting TypeScript to JavaScript: A Step-by-Step Guide

I have this code written in Typescript and I need to convert it to JavaScript const Home = (props) => { return ( <div> {props.name ? 'Hi ' + props.name : 'You are not logged in'} </div> ); }; How can I re ...

How can I transfer data to a different component in Angular 11 that is not directly related?

Within the home component, there is a line that reads ...<app-root [message]="hii"> which opens the app-root component. The app-root component has an @input and {{message}} in the HTML is functioning properly. However, instead of opening t ...

Is there a way for me to manually designate certain domains with the rel="follow" attribute while assigning all other external links with the rel="nofollow" attribute?

I'm working on developing a community platform similar to a social network. I've implemented a code that automatically makes all external links nofollow. However, I would like to create a feature that allows me to remove the nofollow attribute f ...

Utilizing variables to access specific elements within an array

I'm attempting to develop a menu that enables users to navigate through folders in order to batch copy and sync files. However, I'm encountering challenges when it comes to accessing array values based on user inputs. While they display correctly ...

Verifying API access with custom settings using the got module

I'm having some trouble with a basic API call that requires authentication using the got library. I tried using the options parameter to pass my username and password, but I keep getting an HTTPerror. Could someone please review my usage of the optio ...

I am sending an AJAX request to a remote server in order to retrieve access records

Currently, I am attempting to retrieve data by sending an ajax request to a remote server controller from my current remote page. Below is the code for my first remote view page: <?php include 'header.php'; ?> <script src="/assets/js/ ...

What is the process for publishing an npm package to a Nexus group repository?

After installing Nexus Repository Manager OSS version 3.2.1, I successfully ran it on my local machine. Setup Within Nexus, I have set up three NPM repositories: [PUBLIC] - acting as a proxy for the public npm registry [PRIVATE] - designated for my own ...

Iterate through a intricate array of JavaScript objects to extract their values

Looking for ways to extract total calorie and nutrition information from a large document displaying the nutritional data of a simulated recipe. Please review the codesandbox json file first. The objective is to capture the total calories and nutritive c ...

What is the process for invoking an External Javascript Firestore function within a Typescript file?

Trying to figure out how to integrate a Firestore trigger written in an external JavaScript file (notifyNewMessage.js) into my TypeScript file (index.ts) using Node.js for Cloud functions. Both files are located in the same directory: https://i.stack.imgu ...

Dynamic shopping cart with Vue.js

Currently, I am working on a shopping cart project using Vue.js and Vuetify. I need help figuring out how to capture the boolean value true or false and adjust the total price in the amount based on whether it is true or false. Any suggestions? <v-con ...

Recursive functions that request input from the user

Currently in the process of developing a fun little script to help me organize and rate the movies in my personal collection. Among my list are a number of different movie titles that desperately need to be organized. The plan is to implement a merge-sort- ...

New solution for Java applet requiring communication with browser using JavaScript

Within our web platform, we have been utilizing a Java applet to interact with the MS Word application using jacob jar. This allows users to open, edit, and automatically upload files to the server upon saving. However, due to Google Chrome discontinuing ...

Mobile Devices Experiencing Issues with Proper Resizing of Three.JS Panorama

I'm currently working on a project using Three.Js and its device orientation library to create a panorama that users can navigate by moving their phones. Initially, everything looks great as intended: Proper Panorama However, upon refreshing the pag ...

What are the benefits of removing event listeners in Reactjs?

In my opinion, the event listeners need to be reliable and consistent. React.useEffect(() => { const height = window.addEventListener("resize", () => { setWindowSize(window.innerHeight); }); return () => window.remov ...

Downloading a folder in Node.js using HTTP

Currently facing an issue with downloading a folder in node js. The problem arises when I make an HTTP request for a whole folder and receive a stream that contains both the folder and files. Existing solutions (like fs.createWriteStream) only seem to work ...

The Vue.js Vuetify.js error message is saying "A mystery custom element: <v-list-item>, <v-list-item-title> - Have you properly registered the component?"

I followed the instructions from Vuetify Data Iterator Filter section I am able to use various Vuetify components like v-btn, v-card, v-data-table, v-data-iterator, and more. However, I encountered errors only with <v-list-item> and <v-list-item ...

PHP move_uploaded_file() function encountering an issue

As a newcomer to PHP, I am exploring the move_uploaded_file() function. I initiate an HTTP POST request from JavaScript/jQuery to a PHP file hosted on a Microsoft Azure server. The request includes an audio blob like so... mediaRecorder.ondataavailab ...