How can JavaScript for loops be utilized to locate values that are previous, equivalent, within a range,

I'm feeling a bit puzzled right now. Allow me to provide a straightforward example to showcase the issue I'm encountering.

I have certain expectations from the code: when current = 3, it should return 'before'; when current = 4, it should return 'key-two'; when current = 5, it should return 'between'; when current = 7, it should return 'key-two'; and when current = 8, it should return 'after'.

Unfortunately, the code isn't producing the expected results. When I set current to 7, it returns 'key-two'; when I set it to 8 or higher, it returns 'after'; and any other number results in 'between'.

let items = []
items['key-one'] = 4
items['key-two'] = 7

let current = 3

let results = ''

for(let key in items) {
    let keyOne = ''
    let keyTwo = ''
    if (key === 'key-one') {
        keyOne = items[key]
    }
    if (key === 'key-two') {
        keyTwo = items[key]
    }
    if (current < keyOne) {
        results = 'before'
    }
    else if (current === items[key]) {
        results = key
    }
    else if (current > keyOne && current < keyTwo) {
        results = 'between'
    }
    else if (current > keyTwo) {
        results = 'after'
    }
}
document.write(results)

Answer №1

When the loop iterates, it creates a new variable each time. To avoid this, it's better to declare keyOne and keyTwo outside the loop.

let items = []
items['key-one'] = 4
items['key-two'] = 7

let current = 3

let results = ''
let keyOne = ''
let keyTwo = ''
    
for(let key in items) {

    if (key === 'key-one') {
        keyOne = items[key]
    }
    if (key === 'key-two') {
        keyTwo = items[key]
    }
    if (current < keyOne) {
        results = 'before'
    }
    else if (current === items[key]) {
        results = key
    }
    else if (current > keyOne && current < keyTwo) {
        results = 'between'
    }
    else if (current > keyTwo) {
        results = 'after'
    }
}
document.write(results)

While this will make your code work, there are ways to enhance it. Consider using the following method:

function positionInRange(point, low, high){
  return point > high ? "after" :
    point < low ? "before" :
    point > low && point < high ? "between" :
    point == low ? "key-1" : "key-2"
}

var items = {
  "key-1": 4,
  "key-2": 7
}

var results = positionInRange(3, items['key-1'], items['key-2']);
document.write(results)

Answer №2

There is a simpler way to achieve the desired outcome without using a for loop. Here is an alternative code snippet:

let items = {};
items['key-one'] = 4
items['key-two'] = 7

let current = 4

let results = ''
let keyOne = items['key-one'];
let keyTwo = items['key-one'];

if (current < keyOne) {
  results = 'before'
} else if (current === keyOne) {
  results = "key-one";
}else if (current === keyTwo) {
  results = "key-two";
} else if (current > keyOne && current < keyTwo) {
  results = 'between'
} else if (current > keyTwo) {
  results = 'after'
}

document.write(results)

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

Using NodeJS Script in conjunction with Express and setInterval

Feeling stuck and unable to find clear answers for the best solution. I have a Node.js app that serves APIs with MongoDB as the database. I created a setInterval within the request to update the data every 30 seconds. This was done to prevent the Node.js ...

wiping out a column in Excel spreadsheets with the help of Node.js or its corresponding node modules

I've attempted various approaches without success. Can you provide guidance on deleting and adding columns within an Excel sheet using Node.js? ...

JavaScript function for automatic scrolling to the bottom of the page is not functioning as expected

I'm working on incorporating a terminal/console feature into my website. I came across the JavaScript functions for scrolling down a page, namely window.scrollTo(0,document.body.scrollHeight); and window.scrollTo(0,document.querySelector(".fakeSc ...

Modifying script variables using the Chrome console

There is a button on the website that looks like this: https://i.sstatic.net/G7PBF.png Clicking on this button triggers the following script: https://i.sstatic.net/rIdLW.png function count(){ let downloadTimer; var timeleft = 30; downloadTimer = setInte ...

Showcasing an image stored in an HTML file on a Vue.js webpage

I'm currently facing an issue with displaying a local image saved in an HTML file on my Vue.js page. I attempted to store the content of the HTML file into a variable using the code below: computed: { compiledHtml: function() { return this.a ...

React: When component is suspended, the useEffect hook is not triggered

Exploring the world of react hooks and react suspense has led me to creating a custom hook called useApolloQuery. This hook is designed to fetch data and utilize a promise to wait until the data is loaded. My approach involves placing the data fetching lo ...

"Addressing the issue of ineffective form validation for empty or whitespace inputs

I've been working on creating a form and everything seems to be going well except for the validation aspect. It doesn't highlight when intentionally left blank or filled with spaces. I have included "required" in the HTML which partially achieves ...

Tips for enlarging the box width using animation

How can I create an animation that increases the width of the right side of a box from 20px to 80px by 60px when hovered over? What would be the jQuery code for achieving this effect? ...

Guide on incorporating file uploads in an Angular 6 project

I am currently working on creating a component where I have implemented a file upload function in a child component and am attempting to use that component's selector in another one. Here is my project structure: - upload : upload.component.html up ...

Having trouble with implementing Nested routes in Vuejs?

main.js import Vue from "vue"; import App from "./App.vue"; import VueRouter from "vue-router"; import HelloWorld from "./components/HelloWorld"; import User from " ...

What is preventing us from setting a child's width and height to match that of the parent element?

Parent element is a div with a width of 300px and a height of 40px, containing a child input. In the following code snippet: myinput = document.getElementById("e2"); myinput.style.cssText ='width:100%;height:100%;padding:0px;margin:0px;' div{ ...

Attempting to utilize solution for the "ajax-tutorial-for-post-and-get" tutorial

I've been exploring the implementation of the second answer provided in a post about Ajax tutorials on a popular coding forum. Despite following the instructions, I encountered an issue where the $.ajax script, triggered by an "onclick" function, only ...

When an object is not empty, the function Object.getOwnPropertyNames will still return an empty array

In my code, I am filling $scope.master with data from a csv file. When I populate $scope.master within the function, all the data is present. This can be observed in the log output displayed below. However, outside of the function, although $scope.master ...

Tips for presenting HTML source code with appropriate tag coloring, style, and indentation similar to that found in editors

I need to display the source code of an HTML file that is rendered in an iframe. The source code should be shown with proper tag colors and indentations similar to editors like Sublime Text. https://i.stack.imgur.com/IbHr0.png I managed to extract the sour ...

What is the best way to display and conceal a loader in order to reveal additional posts?

How can I display a loader when the user clicks on the "load more posts" button, show it while the posts are loading, and hide it once the posts have been successfully loaded? Additionally, I want to show the loader again when the user clicks on the button ...

I'm having trouble figuring out why my Vue method isn't successfully deleting a Firebase object. Can anyone offer some guidance

What I am trying to achieve: I have been struggling to use the remove method from Firebase. I have read the documentation, but for some reason, it is not working as expected. Retrieving data using snapshot works fine, but when I try to delete using the re ...

What is the method for specifying a .php page as the html source when using Ext.Panel?

I have a current situation where I manually set the html for an existing panel using a variable in the following way: var htmlContent = '<H1>My Html Page'; htmlContent += '[more html content]]'; var newPanel = new Ext.Panel({ ...

Switch out the ajax data in the input field

Is there a way to update the value in a text box using Ajax? Below is my code snippet: <input type="text" id="category_name" name="category_name" value="<?php if(isset($compName)) { echo ucfirst($compName); ...

What are some methods for resolving the problem of CORS policy blocking access to retrieve data from Yahoo Finance?

Currently, I am attempting to retrieve the price of a stock within my pure React App by utilizing fetch. When I try to fetch without any options or configurations, using fetch(url), I encounter the following error: Access to fetch at 'https://quer ...

Alert-Enabled Random Number Generation Tool

I'm struggling to create a program that randomly generates a number between 1 and 20. If the number is less than 10, it should display "fail," and if it's greater than 10, it should display "success." I can't seem to figure out where I went ...