Sending back various results in a javascript function

I am attempting to correlate test scores with values from the level array in order to extract selected values into an output array. However, when I execute the following script in the Firebug console, I encounter the error message "TypeError: level is undefined". This confuses me as I believe that the level variable is properly defined; perhaps the error is originating from a different source.

var level = [[905,990,"91% - 100%","International Professional Proficiency","Able to communicate effectively in any situation"],
    [785,900,"79% - 90%","Working Proficiency Plus","Able to satisfy most work requirements with language that is often, but not always, acceptable and effective"],
    [605,780,"61% - 78%","Limited Working Proficiency","Able to satisfy most social demands and limited work requirements "],
    [405,600,"41% - 60%","Elementary Proficiency Plus","Can initiate and maintain predictable face-to-face conversations and satisfy limited social demands"],
    [255,400,"26% - 40%","Elementary Proficiency","Speaker has functional, but limited proficiency. Able to maintain very simple face-to-face conversations on familiar topics"],
    [10,50, "0 - 25%","Basic Proficiency","Able to satisfy immediate survival needs"]];

function between(x, min, max) {                     
  return x >= min && x <= max;
}

var newProfic =  function profLevel(x, level) {
    var prof1, prof2, prof3;
    for(var i=0; i<level.length; i++) {
      if( between(x, level[i][0], level[i][1])) {
        prof1 = levell[i][2];
        prof2 = level[i][3];
        prof3 = level[i][4];
      }     
    }
    return  [ prof1,   prof2,  prof3 ];
  }

  var profic = newProfic();
  var prof1 = profic[0];
  var prof2 = profic[1]; 
  var prof3 = profic[2];  
  newProfic( 300,  level);

Any insights or assistance would be greatly appreciated. Thank you

Answer №1

I recommend utilizing Array#filter followed by Array#map to extract the desired elements.

This suggestion accounts for scenarios where there may be zero, one, or multiple result sets.

var level = [[905, 990, "91% - 100%", "International Professional Proficiency", "Able to communicate effectively in any situation"], [785, 900, "79% - 90%", "Working Proficiency Plus", "Able to satisfy most work requirements with language that is often, but not always, acceptable and effective"], [605, 780, "61% - 78%", "Limited Working Proficiency", "Able to satisfy most social demands and limited work requirements "], [405, 600, "41% - 60%", "Elementary Proficiency Plus", "Can initiate and maintain predictable face-to-face conversations and satisfy limited social demands"], [255, 400, "26% - 40%", "Elementary Proficiency", "Speaker has functional, but limited proficiency. Able to maintain very simple face-to-face conversations on familiar topics"], [10, 50, "0 - 25%", "Basic Proficiency", "Able to satisfy immediate survival needs"]];

function between(x, min, max) {
    return x >= min && x <= max;
}

function profLevel(x, level) {
    return level.filter(function (a) {
        return between(x, a[0], a[1]);
    }).map(function (a) {
        return [a[2], a[3], a[4]];
    });
}

console.log(profLevel(300, level));
.as-console-wrapper { max-height: 100% !important; top: 0; }

This approach assumes there will be only one resulting set of data.

var level = [[905, 990, "91% - 100%", "International Professional Proficiency", "Able to communicate effectively in any situation"], [785, 900, "79% - 90%", "Working Proficiency Plus", "Able to satisfy most work requirements with language that is often, but not always, acceptable and effective"], [605, 780, "61% - 78%", "Limited Working Proficiency", "Able to satisfy most social demands and limited work requirements "], [405, 600, "41% - 60%", "Elementary Proficiency Plus", "Can initiate and maintain predictable face-to-face conversations and satisfy limited social demands"], [255, 400, "26% - 40%", "Elementary Proficiency", "Speaker has functional, but limited proficiency. Able to maintain very simple face-to-face conversations on familiar topics"], [10, 50, "0 - 25%", "Basic Proficiency", "Able to satisfy immediate survival needs"]];

function between(x, min, max) {
    return x >= min && x <= max;
}

function profLevel(x, level) {
    var index = -1;
    level.some(function (a, i) {
        if (between(x, a[0], a[1])) {
            index = i;
            return true;
        }
    });
    if (index >= 0) {
        return [level[index][2], level[index][3], level[index][4]];
    }
}

console.log(profLevel(300, level));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

The issue at hand is:

ReferenceError: levell is not defined

An extra l was mistakenly added to one of the variables causing this error.


Another mistake found:

var profic = newProfic();

Calling newProfic without specifying the second argument results in it being undefined.

var newProfic =  function profLevel(x, level) {

The second argument is level, hence why it is undefined.

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

Display loader until the document body has finished loading

Many developers have shared solutions for displaying a loader while an element is being loaded. However, my challenge is unique. I want to display a loader before the document body is fully loaded. The issue arises from an AJAX call in my code: var url = ...

Identifying Matching Array Indexes

Received a POST request on one of my pages, below is an excerpt: [shipCountry] => United States [status] => Accepted [sku1] => test [product1] => Test Product [quantity1] => 1 [price1] => 0.00 The request may vary in size, with product ...

AngularJS: Batch processing for saving multiple students simultaneously

I have been working on saving information about students, and I've written the code below. However, I'm unsure how to proceed from here. Any additional information or resources related to this topic would be greatly appreciated. <div ng-contr ...

Ensuring a radio button is pre-selected by default in React by passing in a prop

Assume I have a React function similar to this function Stars({handleStarClick, starClicked}) { if (starClicked === 3) { document.getElementById('star3').checked = true } return ( <div className="rate"> ...

Cannot utilize the subscribed output value within the filter function

I am in need of assistance with my Angular 7 project. I have successfully implemented a service to call a Json file and output an object array. However, I am facing an issue when trying to filter the objects in the array based on a specific property called ...

Tips for showing ng-repeat items solely when filters are applied by the user

Is there a way to only display elements when a user uses a filter? For instance: $scope.elements = [{name : 'Pablo', age : 23}, {name : 'Franco', age : 98}]; <input type="text" ng-model="searchText" /> <div ng-repeat="elemen ...

Unexpected error in boot.ts file in Angular 2

I am currently experimenting with various folder arrangements for Angular 2. When attempting to launch a local server, I encounter the following error: Uncaught SyntaxError: Unexpected token < Evaluating http://localhost:3000/prod/app/TypeScript/bo ...

Having trouble parsing FormData in the django backend

Greetings everyone! I hope you are all doing well. I've been working on a custom form that needs to be sent to the Django backend using an AJAX request. The challenge I'm facing is that when I wrap the form into FormData, it works fine on the fro ...

Using an AJAX post request will result in receiving an HTML element, especially when an attachment is included with Paperclip

I've created an innovative application where users can share their stories through ajax submissions and engage with other readers by commenting on the stories using ajax as well. The technology stack I'm working with includes Rails 3.0.3, ruby 1. ...

Change the size of a particular div upon hovering over another element

I'm trying to figure out how to scale my div with text when a user hovers over a button, but I've tried various operators like >, ~, +, - with no success. section { background: #000; color:#fff; height: 1000px; padding: 150px 0; font-family ...

Exploring the concept of D3 data binding key accessor

Exploring D3 for the first time, I am working on a basic example to grasp the concept of data binding. My setup includes an array of colors, a function to add a color, and a function to remove a color based on index. However, I'm facing issues with t ...

Top method for managing missing sub-documents in MongoDB query outcomes

I've seen this question asked in various forms before, but I'm seeking the most efficient way to manage query results without relying on multiple if statements. Imagine I need to locate a product (sub-document) within a package (document) Packa ...

Is there a way to categorize data and sort it by using an action and reducer in redux?

I have developed a filtering system that allows users to filter data by different categories such as restaurants, bars, cafes, etc. Users can select whether a specific category should be displayed or not, and this information is then sent to the action and ...

Add an event listener to a specific class in order to control the visibility of its child elements by

Whenever I click on the "title text" link, the <ol> element refuses to hide, despite my efforts. After thoroughly reviewing the jQuery documentation and scouring Stack Overflow for answers related to .click(), .children(), .toggle(), and .hide(), I a ...

I would like to exclude the item within my ng-repeat loop using ng-if

I'm attempting to utilize ng-if within ng-repeat in order to create Accordions. Depending on the condition value, I want certain items to be skipped in the ng-repeat. For example, if item.condition is true, then only display the accordion. The code b ...

Incorporating a JSON file through a script element

A customized I18n plugin has been developed to accept various languages through json files. The goal is to simplify usage for users by allowing them to easily insert their json package directly into a page along with the script: <script id="pop-languag ...

"Eliminate any inline styling from a string element with the power of JavaScript/j

If I have the following string: let sentence = '<h1 style="lots of class"> </h1><h2> <p style="bunch of class"> </p> <p style="bunch of class"> </p></h2>'; This string contains multiple elements a ...

Trouble with updating a variable within a loop in Cypress

During my experience with writing Cypress tests, I came across an issue that is preventing me from updating a specific variable. The goal of my test is to run a loop and update the questionId variable within each iteration for making API queries. However, ...

Guide for storing dictionary values into an Array using VBA without referencing

My current process involves transferring data from Excel to the dashing.io dashboard using JSON. The data being sent includes multiple sets of data tuples like [{"Group":"Interface","progress";"10"},{"Group":"HMI","progress";"20"}] Currently, I am utili ...

Eliminating the selected option from the dropdown menu after it has been added with Angular

HTML Code <!doctype html> <html ng-app="plunker"> <head> <meta charset="utf-8> <title>AngularJS Plunker</title> <link rel="stylesheet" href="style.css"> <script> document.write("<base href=&b ...