Calculating totals within arrays that are nested, then providing the resulting object

Seeking assistance with a Javascript problem due to being new to the language.

I am trying to create a function that calculates feedback scores based on specific criteria. The goal is to iterate through an array containing nested arrays and increment the properties negative, neutral, or positive based on the score given (below 3, between 4-6, or 7-10 respectively).

However, all I'm seeing in the console log is:

{positive: 0, negative: 0, neutral: 0} 

Clearly, this output is not what I expected. What am I doing wrong?

function gatherFeedback(feedbackArray) {
  let result = {
    positive: 0,
    negative: 0,
    neutral: 0
  };

  if (feedbackArray > 0) {
    for (let i = 0; i < feedbackArray; i++) {
      if (feedbackArray[i][1] >= 7) {
        result.positive++
      } else if (feedbackArray[i][1] <= 3) {
        result.negative++
      } else if (feedbackArray[i][1] > 3 && feedbackArray < 7) {
        result.neutral++
      }
    }
  }
  return result;
}

console.log(gatherFeedback([
  ['feedback1', 10],
  ['feedback2', 3],
  ['feedback3', 6]
]))

Answer №1

The primary issue can be found in the following line:

if(feedbackArray > 0){

Comparing an array to an integer will result in the array being converted into a string. In this case, it becomes:

"feedback1,10,feedback2,3,feedback3,6"

When compared to 0, the result is false (refer to this link for more information), causing the loop not to execute. The same issue arises in the next line:

i < feedbackArray

A simpler solution is to employ a for...of loop and streamline the if/else structure as shown below:

function gatherFeedback(feedbackArray) {
  let result = {
    positive: 0,
    negative: 0,
    neutral: 0
  };

  for (let f of feedbackArray) {
    if (f[1] >= 7) {
      result.positive++
    } else if (f[1] > 3) {
      result.neutral++
    } else {
      result.negative++
    }
  }
  return result;
}

console.log(gatherFeedback([
  ['feedback1', 10],
  ['feedback2', 3],
  ['feedback3', 6]
]))

Answer №2

Update your code to the following:

function analyzeFeedback (feedbackData) {
    let analysis = {positive: 0, negative: 0, neutral: 0};
    if(feedbackData.length > 0){
        for(let j = 0; j < feedbackData.length; j++) {
            if(feedbackData[j][1] >= 7) {
                analysis.positive++
            } else if(feedbackData[j][1] <= 3){
                analysis.negative++
            } else if (feedbackData[j][1] > 3 && feedbackData[j][1] < 7) {
                analysis.neutral++
            }
        }   
    }
    return analysis;
}  

Answer №3

Utilize the array property .length:

function analyzeFeedback(feedbackArray) {

  let analysis = {
    positive: 0,
    negative: 0,
    neutral: 0
  };

  if (feedbackArray.length > 0) {
    for (let i = 0; i < feedbackArray.length; i++) {
      if (feedbackArray[i][1] >= 7) {
        analysis.positive++
      } else if (feedbackArray[i][1] <= 3) {
        analysis.negative++
      } else if (feedbackArray[i][1] > 3 && feedbackArray [i][1] < 7) {
        analysis.neutral++
      }
    }
  }
  return analysis;
}

console.log(analyzeFeedback([
  ['review1', 10],
  ['review2', 3],
  ['review3', 6]
]))

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

Tips for effectively displaying camera.position.set (x,y,z) and camera.lookAt (x,y,z) within a three.js environment

While going through the tutorial on drawing lines in three.js documentation, I came across this code snippet: The code seems to be perfectly fine without any issues. <!DOCTYPE html> <html> <head> <meta charset="utf-8& ...

Tips for managing encoding when transmitting values through ajax

When working in WordPress, I encountered an issue with an Ajax call where a value was being sent inaccurately. blow = \'blo\ Upon receiving the value on the server end, it appeared to have an extra backslash (\). blow = \\& ...

Discover which sub package is needed by running Npm check

While executing the command npm install, I encountered this error message: The package "getSnapshot-pkg-repo@^1.0.0" required by "conventional-changelog-core@^2.0.11" could not be found on the "npm" registry. I am uncertain about the source of this i ...

The JavaScript object is not being properly posted to the $_POST variable on the PHP page when using vanilla AJAX

Despite my extensive search on the internet and stackoverflow, I have yet to find a solution to my problem. While I understand that JQuery is effective in sending objects, when attempting the same task without the framework, my posts fail to go through to ...

Tips for creating a vertical wave animation of a ribbon using svg

I have an SVG code for a vertical ribbon that I want to add a wave effect to. The wave should start from the top and flow continuously to the bottom, but currently it's not working as expected. @keyframes thread{ from { stroke-dashoffse ...

Ensure that you do not display the result until all Ajax calls have finished processing

When faced with a challenging problem, I persist through multiple attempts and seek your assistance in finding a solution. My current goal is to populate a table with the number of viewers for a specific streamer using the Twitch API. To achieve this, I ...

retrieving tunes from minitune

I am trying to retrieve a list of songs using the tinysong API, which pulls data from Grooveshark. I am making the request through $.ajax and here is what I have so far: $.ajax({ url : 'http://tinysong.com/s/Beethoven?format=json&key=&apos ...

Emphasize specific letters in a word by making them bold, according to the user

In my app, there is a search feature that filters data based on user input and displays a list of matching results. I am trying to make the text that was searched by the user appear bold in the filtered data. For example, if the user searches 'Jo&apos ...

Replicating the performance graph of Windows Task Manager

Looking for a JavaScript library that can replicate the dynamic chart seen on the CPU Usage History section of the Windows Task Manager's Performance tab. Any recommendations would be highly appreciated. ...

Add retrieved data from Modal to an array in a Laravel Controller

While working with my modal in the controller to retrieve data from a MySQL database, I encountered an issue. The query that runs multiple times and the retrieved data needs to be stored in a single array. However, the data is not being stored in the desir ...

Assistance with changing styles

Hey there, I could really use some assistance. I've created a style switcher, but I'm struggling to figure out how to replace the stylesheet properly. Currently, my code empties the <head> element when what I really need is for it to simply ...

Deciphering a JSON array extracted from a Tuple

Exploring the Pebble SDK resources on this page and diving into the capabilities of the httpebble library is my current focus. Let's say the DictionaryIterator* received holds a JSON payload like this: {"0":["Oz Lotto","Powerball","TattsLotto","Supe ...

What is the method for retrieving a JSON type object property that is stored inside a data object in a Vue template?

I am facing an issue with retrieving data from a Vue.js app object. data() { return { group1: { id: 'qd4TTgajyDexFAZ5RKFP', owners: { john: {age: 32, gender: 'man'}, mary: {age: 34, gender: 'wom ...

Generating two fetch requests that run independently

Once we have populated a dropdown menu with fields from a fetch request, the next step is to select one of those fields and trigger another fetch request to retrieve data associated with the selected field. However, we encountered an issue where the secon ...

Is the JavaScript Base64 image data damaged or compromised?

My current task involves selecting an image through an HTML Input and then retrieving the image using Javascript to obtain its Base64/Image Data string. However, the code I have implemented is only returning a partially corrupt or invalid representation o ...

Issue with Nextjs: getServerSideProps causing a blank page to display instead of redirecting to 404errorCode

I am facing an issue on my dynamic page where the external server returns a 404 error if the requested product is not found. However, when using getServerSideProps, instead of redirecting to a 404 page, it shows a blank page. Below is the code snippet: // ...

Guide to verifying the scope of a dynamic array in Javascript

Hey there, I'm currently trying to verify if a value falls within a specific range in a dynamic array. Let's say I have an amount of 3555, and an array of values like [1000,2000,999999]. Typically we would use conditional statements to check for ...

Shuffling an array and returning it using Javascript/Angular

I have been working on implementing a shuffle/unshuffle feature in my Angular application. The concept is simple - there's a single button that, when clicked, will either shuffle an array and return the shuffled order, or if the array has already been ...

Using an UnsafeMutablePointer for an array in a C library

I am currently working on integrating a C library into my iOS project, which is developed using the Swift language. One of my functions requires an input parameter where the output values are stored in a typical C double array: double ar[6]; ///... err = ...

Retrieving the selected date from JqueryUI Datepicker after form submission

I am currently using an inline datepicker that fills in an input textbox. $("#left-calendar").datepicker({ altField: "#left-date-text" }); The left-date-text is located within a form, and upon submission with a submit button, it sends the data to a p ...