Finding the value within a specified range of two numbers in Vue.js

When my code generates a result of 0, I need to determine the corresponding value based on the basic_salary. For example, if the basic_salary is 40,000, it should return the value of "ee": 400.


<table class="table table-hover table-bordered table-sm">
    <thead>
        <tr>
            <th scope="col">Contribution</th>
        </tr>
    </thead>
    <tbody>
        <tr v-for="(fetch, count) in SalaryData">
            <td>
                <input type="text" v-bind:value="deducted = contribution(fetch.basic_salary)">
            </td>
        </tr>
    </tbody>
</table>

Within my methods....


contribution(value){
    return Object.values(this.contriDatas).reduce((acc, val)=>{
        if(value >= val.range_from && value <= val.range_to) {
            return val.ee;
        } else {
            return 0;
        }
    }, 0);
}

This is the data structure of contriDatas


[
    {
        "id": 1,
        "range_from": 1000,
        "range_to": 1249.99,
        "er": 83.7,
        "ee": 36.3,
        "created_at": null,
        "updated_at": null
    },
    {
        "id": 2,
        "range_from": 1250,
        "range_to": 1749.99,
        "er": 120.5,
        "ee": 54.5,
        "created_at": null,
        "updated_at": null
    },
    {
        "id": 3,
        "range_from": 3500,
        "range_to": 3600,
        "er": 300,
        "ee": 300,
        "created_at": null,
        "updated_at": null
    },
    {
        "id": 4,
        "range_from": 4000,
        "range_to": 4500,
        "er": 400,
        "ee": 400,
        "created_at": null,
        "updated_at": null
    }
]

Data structure of SalaryData

[
    {
        "basic_salary": 1300,
    },
    {
        "basic_salary": 50000,
    }
]

Answer №1

When using the Reduce function, the entire array is iterated through, resulting in the value from the last iteration being returned.

If you are looking to locate the correct object and retrieve the ee property, consider using Array.find as shown below:

return Object.values(this.contriDatas)
.find(data => value >= data.range_from && value <= data.range_to)?.ee || 0;

In case of using older browsers, an alternative method could be:

return (Object.values(this.contriDatas)
.find(data => value >= data.range_from && value <= data.range_to) || {ee:0}).ee;

A test code snippet is included to demonstrate that the code functions correctly:

const contriDatas = [{
    "id": 1,
    "range_from": 1000,
    "range_to": 1249.99,
    "er": 83.7,
    "ee": 36.3,
    "created_at": null,
    "updated_at": null
  },
  {
    "id": 2,
    "range_from": 1250,
    "range_to": 1749.99,
    "er": 120.5,
    "ee": 54.5,
    "created_at": null,
    "updated_at": null
  },
  {
    "id": 3,
    "range_from": 3500,
    "range_to": 3600,
    "er": 300,
    "ee": 300,
    "created_at": null,
    "updated_at": null
  },
  {
    "id": 4,
    "range_from": 40000,
    "range_to": 4500,
    "er": 400,
    "ee": 400,
    "created_at": null,
    "updated_at": null
  }
];
const test = value => {
  return Object.values(contriDatas)
  .find(data => value >= data.range_from && value <= data.range_to)?.ee || 0;
}

console.log(test(3500));
console.log(test(100));
console.log(test(1500));

Answer №2

reduce() is used to condense an array of elements into a single value. However, if you are looking to find() the first element in the array that meets a specific condition like

value >= val.range_from && value <= val.range_to
, and retrieve its ee field.

A sample implementation could be:

contribution(value){   
  const data = this.contriDatas.find(x => value >= x.range_from && value <= x.range_to);
  if (data) {
    return data.ee;
  }
  return 0;
},

The find method returns undefined if no element matches the condition, so there is a check to verify if data is truthy. If a matching element is found, its ee value is returned; otherwise, it returns 0.

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

Sending data through URL links in HTML

$.post("/diabetes/ropimages/getcount.php",{patientId:$("#patient_id").val()} ,function(data1){ //alert(data1); var count = data1; var patientId = $("#patient_id").val(); var reportId; for( var i = 1 ; i <= count ; i++) { var imageLink =&a ...

Retrieving the value of a specific image using Jquery

<div id="choose"> <div class="picked"> <img src="/def/image1.png"> </div> <div> <img src="/def/image2.png"> </div> <div > <img src="/def/image3.png"> </div> </div& ...

Adding x days to a Unix timestamp can be achieved by converting the Unix timestamp

Currently, I have the following code snippet: let currentTS = Math.floor(+new Date() / 1000) This code successfully retrieves the current date in a unix timestamp. However, my goal now is to append an additional 14 days to this unix timestamp. Could some ...

Guide to shutting down a print dialogue in a web browser with javascript

Looking for a way to close the print window of a browser using JavaScript or any other method, with JavaScript being the preferred option. Any help on closing the print window for IE, Chrome and Safari would be greatly appreciated. Please assist.. Thank ...

Achieve validation of numerous variables without the need for a string of if-else

If we have three variables, such as firstName, lastName, and email, how can we check if they are empty or not without using multiple if else blocks? let firstName = "John"; let lastName = "Doe"; let email = "john.doe@example.com"; if (firstName.trim() == ...

Display information from a selected card on a separate page upon clicking

I am currently working with a JSON file to display cards on a webpage. The code is sourced from a file named paintings.js and the cards are rendering correctly. However, when I click on a card, it redirects me to a blank paintingInfo.js page. I'm wond ...

Attempting to extract the class name of a tr tag but receiving a result of 'undefined'

I'm struggling to retrieve the class name from a specific <tr> tag. <table cellpadding=5 cellspacing=5> <tr id='cat_abc123' class='class_a'> <td>foo</td> <td><input type=& ...

How can I retrieve the value of $_POST[] immediately after a selection is made in a dropdown box

Is there a way to retrieve the $_POST value immediately after changing the select option without having to submit the form? <select name="cat_id" class="form-control" onChange="this.form.submit();" style="width:300px;"> <?php ...

dispatch email display Twitter Bootstrap notification utilizing Ajax

I'm trying to set up an email sending feature via a contact form. I want it to send the email and display a Bootstrap alert confirming that the email has been sent. Below is the HTML code: https://jsfiddle.net/6rfeas35/. Additionally, here is my PHP c ...

Having trouble sharing content from my React next.js website on social media due to issues with open graph meta tags

I'm currently facing an issue with my Next.js application when trying to share content on Facebook and Twitter. I've made sure to include the necessary open graph meta tags in the document's head section and I'm using React Helmet to dy ...

Stop the React timer count for a moment

I am currently attempting to implement a pause feature in a countdown timer using React. Here is the code snippet: export default function Home() { const timerRef = useRef(180) const [minute, setMinute] = useState(3) const [second, setSecond] = useS ...

Create a distributive and an NPM package using one source code

Creating small open source tools is a passion of mine, and I strive to provide the best experience for my users. My packages usually consist of just one function, so here's what I aim to offer: A JavaScript file that users can easily add by including ...

When embedding HTML inside an Angular 2 component, it does not render properly

Currently, I am utilizing a service to dynamically alter the content within my header based on the specific page being visited. However, I have encountered an issue where any HTML code placed within my component does not render in the browser as expected ( ...

Executing a closure within a promise's callback

Currently, I am working on implementing a queue system for a web application in order to locally store failed HTTP requests for later re-execution. After reading Mozilla's documentation on closures in loops, I decided to create inner closures. When ...

What could be causing the error I'm encountering while running the 'net' module in Node.js?

I am currently working with .net modular and have opened TCP port 6112. var net = require('net'); var server = net.createServer(function (socket) { //'connection' listener }); server.listen(6112, function () { //'listening ...

Detect click outside in JavaScript for closing

While this topic has been discussed before, each issue presents its own unique challenges. Despite trying various solutions and examples for making the submenu close when clicking outside of it, I have not had any success. Is there a way to make the uslug ...

I utilized the "data-target" attribute to ensure the active link retains its style. Is there a way to preserve the style when navigating away from an active link?

Can someone assist me with this re-upload? I need help tweaking my code to maintain style when navigating between pages using the "data-target" attribute. Currently, the style is being lost when moving from the original link (e.g., "link/sub01.html") to a ...

Image malfunction in jquery blockui occurs following multiple AJAX requests, except when within the success function of an AJAX request

I have a perplexing question that has been on my mind. While I am aware of the issue and its resolution, I am struggling to comprehend the underlying reason. There is a particular method that goes through some preliminary steps, validation, saving, and cl ...

I encountered an error in JavaScript where the function .val() is not recognized on the selected answer, throwing

I'm trying to verify if the selected answer is correct and then add +1 to my user score. However, I'm struggling with why my code isn't functioning as expected. Can someone please point out where the bug is or if there's something else ...

Adjust the x-axis on the Vue.js bar chart

I'm currently working on a Vue.js Laravel application where I am trying to incorporate a bar chart using the ApexCharts module. <apexchart ref="apexChart" :options="chartOptions" :series="chartData" type="bar" ...