Exploring the contrast between positive and negative numbers in javascript

I am facing a unique challenge with my Javascript function that counts the number of sorted numbers in an array. Strangely, it seems to work perfectly fine for positive numbers, but when negative numbers are involved, the function treats them as if they were positive. Can anyone provide some insight into why this might be happening?

countUniqueValues = (a) => {
    if(a.length === 0){return 0;}
    
    let i = 0;
    let j = 1;

    while(a[j]){
        if(a[i] === a[j]){
            j++;
        } 
        else if(a[i] !== a[j]){
            i++;
            a[i] = a[j];
        }
    }
    return i+1;
}
console.log(countUniqueValues([-2,-1,-1,0,1])); // returns 2, should actually return 4

Answer №1

To eliminate duplicate primitive values, consider utilizing a Set:

const removeDuplicates = arr => new Set(arr).size;

console.log(removeDuplicates([-3,0,1,2,2]));

Answer №2

const numbers = [3, 7, 2, 9, 4];
let distinctNumbers = numbers.filter(getDistinct);

function getDistinct(value, index, self) {
 return self.indexOf(value) === index;
}

console.log(distinctNumbers.length);

This method is successful! Your previous attempt failed because the variables I or J were not properly incremented.

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

Harness the power of Actions SDK to enhance your Google Assistant experience

I'm struggling to get my custom Actions SDK working on my own server. The actions I've created show up in Google Assistant, but the functionality isn't there - it just closes without any errors being displayed. Here's a snippet of my co ...

Enhance your data visualization with d3.js version 7 by using scaleOrdinal to effortlessly color child nodes in

Previously, I utilized the following functions in d3 v3.5 to color the child nodes the same as the parent using scaleOrdinal(). However, this functionality seems to be ineffective in d3 v7. const colorScale = d3.scaleOrdinal() .domain( [ "Parent" ...

"Performing validation on a number input by using the ng-change event

Im using a number input that dynamically sets the min and max values based on another form field. I have two scenarios: Level 1: Min = 2, Max = 50 Level 2: Min = 5, Max = 1000 I've set up an ng-change event on the input field to check if the entere ...

What causes an AJAX POST request to fail?

While working on a simple HTML page with a form, I encountered an issue with my POST request failing without any response from the server. Can someone please help me figure out what I'm doing wrong? function createRequest(url, body) { var respons ...

Shuffling License Plate characters according to geographic location

I am currently working on a project involving License/Number plate recognition. I have successfully recognized the characters in the input image, but there seems to be a problem with the arrangement. The OCR sometimes outputs the characters in the correct ...

Incorporating HTML elements into a Jade template

Can HTML elements be passed into a jade file? For example, I want to insert text into the p element and nest some content inside the code element within the p element. JSON with string data var news = { one : { title : "Using JSON", body : "Us ...

Tips for transferring binary information from a Node.js socket.io (v2.0.x) server to a client in a web browser

When using Engine.io's send function to send binary data, it appears as binary in DevTools. However, Socket.io handles this data as JSON and sends it as text. Is there a way to access the Engine.io send function through a Socket.io instance? Perhaps ...

Guide to removing all elements belonging to a specific class on a webpage using Google Chrome

If I have elements on a website I am using with classes 'aaa', 'bbb', and 'ccc', and I want to delete or hide all elements with the class 'bbb', how can I accomplish this by changing attributes of elements directly o ...

Error: The function `push` cannot be used on the variable `result` (TypeError)

Here is a snippet from my react component const mockFetch = () => Promise.resolve({ json: () => new Promise((resolve) => setTimeout(() => resolve({ student1: { studentName: 'student1' }, student2: { studen ...

Storing both strings and characters within a two-dimensional array in the C programming language

I am currently working on a project to create a DFA simulation program. The task involves taking user input and storing it in two separate arrays, which will be used as rows and columns. These arrays will then be used to create a 2D table of values. For e ...

What is the process for browserifying the net.Socket module in Node.js?

I'm exploring ways to connect and query my MS SQL database from JavaScript in a web browser (specifically Chrome, not IE as I don't want to use ActiveX controls). I came across this Node library called Tedious and Browserify to help with this tas ...

Exploring a multidimensional PHP array---Navigate through a

Array ( [meta_data] => Array ( [5] => Array ( [id] => 33286 [key] => course_id [value] => FF2342 ) ) ) In order to retrieve the desired information, I cannot rely on using the ind ...

When attempting to check and uncheck checkboxes with a specific class, the process fails after the first uncheck

I have a set of checkboxes and one is designated as "all." When this box is clicked, I want to automatically select all the other checkboxes in the same group. If the "all" box is clicked again, I would like to deselect all the other checkboxes. Currently ...

Optimized layout for efficiently looping through multiple arrays

I have 20 different arrays with variable lengths, each containing unique values that I need to calculate all possible combinations for: #define NUM_ARRAYS 20 #define MAX_LENGTH 12 int arrays[NUM_ARRAYS][MAX_LENGTH]; Currently, I am using nested loops to ...

Combining arrays with multiple dimensions in PHP

I am facing an issue while trying to merge multidimensional arrays into one. Even though I have been using the array_merge function, it seems not to work as expected. Take a look below at the arrays provided: $arr1 = [['title' => 'first ...

Does anyone know of a nodemon alternative that works on Windows?

Is there a Windows-compatible service similar to nodemon that can assist with Nodejs development now that it's available on the Windows platform? ...

What is the best method for fetching data returned by AJAX using PHP?

I have a data structure similar to the one below, which is returned via AJAX to another file: $data = array(); $data['message'] = "You are searching: $domain!"; $data['domain:name'] = "domain.tld"; $data['domain:registrar ...

Send a file using ajax with the help of JavaScript and PHP

Currently, I am looking to implement a method for uploading files using Ajax and JavaScript/PHP without having the page refresh. My initial thought is to use Ajax to send the file using xmlhttp.send(file) and then retrieve it in the PHP script, but I' ...

Consistent manipulation of the DOM through the Drag/Touchmove event

Seeking to incorporate Mobile Components through native Javascript and AngularJS. During my work on developing a Pull To Refresh directive for AngularJS, I utilized the touchmove event on a UL list. The goal was to pull a concealed div over a list with cu ...

JavaScript error: Resource could not be loaded

When I have a js function called by an onclick event in a radio button, it doesn't work if the function is placed in the same ascx file where the radio button is defined. To resolve this issue, I moved the function to the ascx that includes the ascx w ...