Updating elements in an array based on a specified threshold value, all done without the use of conditional if statements in Javascript

I am exploring ways to efficiently solve this particular problem.

Within my dataset is an extensive array of integers:

[170,158,147,139,134,132,133,136,141,.....]

I have predetermined threshold values of 132 and 137.

My goal is to adjust any numbers in the array that are below 132 to a new value, such as 100, and change any number above 137 to another value, like 150.

One approach could be to create a function:


for (i < array.length)
    if(array[i] < 132)
        array[i] = 100;
    if(array[i] > 137)
        array[i] = 150

However, with the size of my array being over 20k elements, this method would be time-consuming due to the numerous conditional statements.

The order of the array must be maintained, eliminating the possibility of sorting.

Perhaps utilizing bitwise operations could provide a more efficient solution for this task.

Answer №1

Consider giving this a try for potentially improved speed:

let givenData=[170,158,147,139,134,132,133,136,141,.....];
let updatedResult=givenData.map(item=> item<132 ? 100 : (item>137 ? 150 : item));

Answer №2

The efficiency of different types of for loops can vary significantly. Using a traditional for loop like

for (i=0; i < array.length; i++) {}
is generally much faster than using for (i in array) {}. Let's compare the speed difference by looking at an example with an array containing 1,000,000 elements:

var bigData = [];
for (var i = 0; i < 1000000; i++) {
  bigData[i] = i;
}

console.time('TEST1');
for (i=0; i < bigData.length; i++) {
    if(bigData[i] < 132)
        bigData[i] = 100;
    if(i > 137)
        bigData[i] = 150
}
console.timeEnd('TEST1');

console.time('TEST2');
for (i in bigData) {
    if(i < 132)
        i = 100;
    if(i > 137)
        i = 150
}
console.timeEnd('TEST2');

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

Detecting collisions on a pixel-by-pixel basis within Javascript/Jquery/Gamequery

Currently, I am working on developing a web game using Jquery with the GameQuery plugin. However, I have encountered an issue where the GameQuery plugin does not support per pixel collision detection, only bounding boxes collision detection. Is there a way ...

Retrieving data from AJAX requests

I have an AJAX code that sends data to the server and returns results including id, name, and quantity. How can I extract and print only the quantity, id, or name? Thank you for your help! <script type="text/javascript"> $("#bto_update_quan ...

What is the best way to organize class usage within other classes to prevent circular dependencies?

The engine class presented below utilizes two renderer classes that extend a base renderer class: import {RendererOne} from "./renderer-one"; import {RendererTwo} from "./renderer-two"; export class Engine { coordinates: number; randomProperty: ...

Tips for sending an array with all its elements from jQuery to PHP

Currently, I am attempting to transfer an array from jQuery to PHP. <input type="checkbox" id="name1" name="name[]" value="name1"> Name1 <input type="checkbox" id="name2" name="name[]" value="name2"> Name2 <input type="checkbox" id="name3" ...

Simple Way to Show API Output in Plain Text (Beginner Inquiry)

I'm a beginner when it comes to using APIs. I'm trying to display the plain text response from this URL on my webpage: However, I'm encountering issues with getting it to work. Here's my code: <script src="https://ajax.googleap ...

Adding a component dynamically with a link click in Angular: A step-by-step guide

I am encountering an issue with my web application setup. I have a navigation bar, a home page with left and right divs, and a view-associates component. My goal is to dynamically add the view-associates component into the home's right div when a spec ...

How do I iterate through two arrays in jQuery/JS and switch a class using an if/else statement?

Currently, I am iterating over two arrays: selectedLabelsTemp which appears as [1,8], and the rosterLabelList...$(this).data looks like [1,8,2,12]. My objective is to ensure that when it enters the if-else statement, $(this) will receive the class check-ac ...

Issue with adding a video to a playlist using Youtube API

While I have successfully implemented GET requests using the Youtube API v3, I am encountering difficulties when trying to make a POST request to add a video to a playlist. Despite trying various approaches such as including the key in the query string, pl ...

How can I utilize a CDN for JavaScript libraries in Gulp?

As a newcomer to AngularJS and Gulp, I recently encountered an example where certain libraries are copied by Gulp from the 'node_modules' folder into a 'js/lib/angular2' directory: gulp.task('libs', function() { return gulp. ...

How can I retrieve the top-level key based on a value within a JSON object nested in JavaScript?

If I have the value Africola for key name in the following nested JSON structure, how can I retrieve its corresponding upper-level key 'barID1' using JavaScript? { "barID1": { "address": "4 East Terrace, Sydney NSW 2000", "appStoreURL" ...

What is the process to manually trigger hot reload in Flutter?

I am currently developing a Node.js application to make changes to Flutter code by inserting lines of code into it. My goal is to view these updates in real-time. Is there a way to implement hot reload so that every time I finish writing a line in the file ...

Cors policy error encountered in Node.js application and React application

I have developed an application using Node.js and React. I am currently hosting the server side on node.kutiza.com and the client side on finanu.kutiza.com through Namecheap. However, when I try to make a request to node.kutiza.com, I encounter an error me ...

How can I structure the response from HttpClient to make it compatible with *ngFor

I need assistance in solving a minor issue. I am working with data from a REST API, which is returned as an array of objects. After receiving this data in my service, I attempt to transform it and push it to a subject to notify my component about the arriv ...

What is the best method for retrieving the entire row data based on the maximum value in a column?

function findMaxValue() { var highestValue = Math.max.apply(Math, $('.sira').map(function() { return $(this).text() })) alert(highestValue); } <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js"& ...

Utilizing MutationObserver in JavaScript for Streamlined Code Execution

One of my functions utilizes a MutationObserver to track attribute changes in a specified element and logs them to the console. Below is an example where I pass 'card' elements in a foreach loop: track_attr_changes(element); The parameter ' ...

Exploring the keyof operator in Typescript for object types

Is there a way to extract keys of type A and transfer them to type B? Even though I anticipate type B to be "x", it seems to also include "undefined". Why does the keyof operator incorporate undefined in the resulting type? It's perplexing. I kn ...

Tool for controlling the layout of the viewport with Javascript

I have experience using ExtJS in the past to create dashboards, and one of my favorite features is the full-screen viewport with a border layout. This allows for easy splitting of a dashboard into panels on different sides without creating excessive scroll ...

Combining Arrays in a Single External Loop

My goal is to restructure an array called "item_code" nested within another array. The item_code array contains multiple keys, with each key holding a comma-separated list of USExxxxx values. Array ( [name] => Wes [email] => <a href="/cdn ...

Check the box to track the current status of each individual row

Recently, I encountered an issue with a form containing dynamic rows. Upon fetching records, my goal was to update the status of selected rows using checkboxes. Although I managed to retrieve checkbox values and dynamic row IDs successfully in the console ...

NPM: Implementing a "post-install" hook that is only executed internally and not for package consumers

Currently, I am in the process of developing an NPM module and would like to automate certain tasks following every npm install while working on the module locally. However, it is crucial that these tasks are not executed when users of my library perform ...