Transform an array of values into a new array with a set range

Looking for a solution in JavaScript! I currently have an array of values:

var values = [3452,1234,200,783,77]

I'm trying to map these values to a new array where they fall within the range of 10 to 90.

var new_values = [12,48,67,78,90]

Does anyone know how this can be done in plain JS?

Feeling a bit stuck :( Thank you

Answer №1

If you are referring to the concept of mapping (exchanging one value for another), then you can use Array#map:

var new_array = array.map(function(value) {
    return /*...your calculation on value here...*/;
});

This function will iterate through each value in the array, apply your specified calculation, and create a new array based on the returned values. (Sorry, I couldn't understand how 3452 turns into 12 or 1234 into 48, etc.)

For example, to double each value in an array:

var array = [1, 2, 3, 4];
var new_array = array.map(function(value) {
  return value * 2;
});
console.log(new_array);

If you mean filtering values within a specific range, then you would use Array#filter:

var new_array = array.filter(function(value) {
    return value >= 10 && value <= 90;
});

This function will evaluate each value against your conditions and include only those that satisfy them in the new array. Here, "between 10 and 90" includes both 10 and 90.

For instance:

var array = [3452, 1234, 200, 783, 77];
var new_array = array.filter(function(value) {
    return value >= 10 && value <= 90;
});
console.log(new_array);


In modern versions like ES2015 (or "ES6") and beyond, you can write these operations more succinctly:

let new_array = array.map(value => /*...your calculation on value...*/);

Or

let new_array = array.filter(value => value >= 10 && value <= 90);

Answer №2

To secure in place:

const updated_values = [500,234,10,789,87].map(number => Math.min(100, Math.max(number, 50)));

To screen and select:

const filtered_values = [500,234,10,789,87].filter(num => 50 < num && num < 100));

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

The HTTP request is being executed twice for some reason unknown to me

import React, {useState, useEffect} from 'react' export function UseStateExample() { // This is a named export that must be used consistently with {} when importing/exporting. const [resourceType, setResourceType] = useState(null) useEffect ...

Best practices for authenticating methods with Google signin in Angular projects

I have made significant progress towards getting the Google signin feature to work, reaching 95% completion. However, I am currently facing two issues with the code. Here is a simplified version of my current implementation: loginWithGoogle(): void { //t ...

Is there a way to prevent HTML rendering with Javascript within a JSP page?

When a user accesses our site from China, we need to block certain assets to optimize the speed of the site. For example, resources from Facebook need to be blocked from loading altogether. The challenge is that this task must be accomplished using JavaSc ...

Node.js and TestCafe encountered a critical error: Inefficient mark-compacts were performed near the heap limit, resulting in an allocation failure. The JavaScript heap ran

While executing my test scripts in Node v14.6.0, I encountered the following problem. Here are some of the options I've tried: I attempted to increase the Node Heap Size but unfortunately had no success: export NODE_OPTIONS=--max_old_space_size=4096 ...

React and Material-Ui utilize class definitions in .js files, which are then passed as strings to components

I am attempting to define a class within my .js file in order to utilize the material-ui theme object and pass it as a string to a component since the component's prop only accepts strings. Unfortunately, the React-Dropzone import does not accept a cl ...

Translating from a higher-level programming language to a lower-level programming language

Is compilation effectively the transformation of high-level programming languages (HLL) into machine code or low-level language? If so, why is TypeScript (a HLL) compiled to JavaScript (also a HLL) instead of being compiled to a low-level language? ...

The absence of HTML and CSS is preventing the inclusion of an Ajax image viewer, back button, and

Currently, I am experimenting with jQuery and JavaScript to create an ajax overlay image viewer for a PHP website. After adding this code snippet at the end of the 'gallery page', I can successfully open the viewer and navigate using the next and ...

JavaScript method to prevent users from entering numbers as the first two characters, with all subsequent characters being numbers only

I need a specific requirement for my form. The textbox field in my form is labeled "DEA License number", and I want it to only allow the user to enter alphabetic characters for the first two characters, followed by numbers afterward. I am looking to impl ...

Using Javascript's OnChange event to dynamically update data

Attempting to achieve a seemingly straightforward task, but encountering obstacles. The goal is to trigger a JavaScript onChange command and instantly update a radar chart when a numerical value in a form is altered. While the initial values are successful ...

What could be the reason for my jQuery call displaying as undefined?

How can I extract a URL from an <a> tag and show the first paragraph of the linked page below the title? At the moment, it just shows 'undefined'. Here's my HTML: <section class="community"> <div class="news"> <ul cla ...

Reveal the table only once a search has been completed

Currently, I am in the process of developing a small project and my aim is to have the table with the results appear only upon clicking the button or initiating a search. If you are interested, you can view it at this link: . My objective is to keep the t ...

Tips for transitioning from custom CSS to Material UI's CSS in JS

I came across a project where someone implemented components with custom CSS. One interesting thing I noticed was a wrapper component, similar to Material UI's Container or just a simple div with applied styles. export const Container = styled.div` ...

Restrict access to table records by specifying an array of row identifiers

Hi everyone, I've encountered a small issue. Just to provide some background, I have a table with checkboxes. Each row in the table has an associated ID, and when selected, I receive an array like this: const mySelectedRoles = [1997, 1998, 1999] Once ...

Ways to Soothe Long Polling

Currently, I am developing a basic chat feature using AJAX in a function that triggers a setTimeout call to itself upon successful execution. This occurs approximately every 30 seconds. While this setup serves its purpose, I am seeking a more immediate not ...

What could be the root cause behind the error encountered while trying to authenticate a JWT?

I've been working on integrating a Google OAuth login feature. Once the user successfully logs in with their Google account, a JWT token is sent to this endpoint on my Express server, where it is then decoded using jsonwebtoken: app.post('/login/ ...

How can it be that "Function" actually functions as a function?

In JavaScript, there exists a function called "Function". When you create an instance of this function, it returns another function: var myfunc = new Function('arg1','arg2','return arg1+arg2'); In the above example, the vari ...

What are the steps to integrate mp3 music into my web application?

Does anyone have experience implementing auto-resume mp3 music on a web application so that the music continues to play even when the user changes pages? I would like the music to seamlessly play as the user navigates through my web application. Can someo ...

Develop an onclick function with an href attribute

I am interested in transforming links into AJAX versions whenever possible. To achieve this, I plan to implement a function called replaceLinks that will add an onClick handler to each link on the page and trigger ajaxPageWSM(href). This is what I currentl ...

Pagination in DynamoDB: Moving forward and backward through your data

Currently, I am utilizing DynamoDB in combination with NodeJS to display a list of objects on the user interface. Given that DynamoDB can only process 1MB of data at a time, I have opted to implement pagination. This allows users to navigate between pages ...

Utilizing inline javascript to dynamically update the selected option of a radio button

A form on my website includes two radio buttons: one labeled 'trigger_unit' and the other labeled 'normal_unit'. In addition, there is a select drop-down menu with four values and a default NULL option. <select rel="dropdown" name=" ...