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

Conceal the child elements underneath a selected element using jQuery

I am currently working on an order form within a website and the HTML code is structured as below: <table class="variations"> <div class="tawcvs-swatches" data-attribute_name="attribute_pa_t-shirt- one-color"> <span class="swat ...

String ES6 syntax immediately after function

return pool.query`select * from mytable where id = ${value}` How can the code snippet above be rewritten in full JavaScript? I attempted to use: return pool.query(`select * from mytable where id = $(value)`) but it seems like there is a difference. Th ...

A Vue computed property is returning the entire function instead of the expected value

One of my computed properties is set up like this: methods: { url_refresh: function (id) { return `${this.url_base}?start=${Date.now()}` } } However, when I attempt to print the value on mount: mounted() { console.log(this.url_refresh) ...

Addressing memory leaks in React server-side rendering and Node.js with setInterval

Currently in my all-encompassing react application, there's a react element that has setInterval within componentWillMount and clearInterval inside componentWillUnmount. Luckily, componentWillUnmount is not invoked on the server. componentWillMount( ...

The function signature '() => void' cannot be assigned to a variable of type 'string'

Encountering an issue in Typescript where I am attempting to comprehend the declaration of src={close} inside ItemProps{}. The error message received reads: Type '() => void' is not assignable to type 'string'. Regrettably, I am un ...

Establishing a connection to MongoDB using JavaScript

Currently, I'm working on a fun little project revolving around a web calendar. For this project, I've decided to integrate mongoDB into it. Fortunately, I have successfully configured MongoDB and established a connection with PHP. However, I am ...

Step-by-step guide for dynamically including dropdown options

Is there a way to dynamically add a dropdown using JavaScript? I currently have a dropdown with numbers that creates another dropdown when selected. However, I want to add the dynamic dropdown through JavaScript. How can I achieve this? Below is the PHP ...

Is there a way to use the property of an object to perform a merge sort, rather than relying on an Array?

Query About Sorting JSON Object in JavaScript In search of the most efficient method to sort a large JSON object based on a specific property, I turned to JavaScript. My initial thought was to utilize a merge sort algorithm for this task due to its speed. ...

The type '{}' is lacking the 'submitAction' property, which is necessary according to its type requirements

I'm currently diving into the world of redux forms and typescript, but I've encountered an intriguing error that's been challenging for me to resolve. The specific error message reads as follows: Property 'submitAction' is missing ...

Node Signature Generation for Gigya Comment Notifications

I am currently using the Gigya Comment Notification service within my node application and attempting to generate a valid signature. Despite following the documentation, my code is producing an incorrect hash. Below is the code I am using: var crypto = r ...

Disallow/bound the position of the marker on Google Maps

Is there a way to restrict the placement of markers on a map? I am looking for a solution that allows me to limit the marker position within a specific area, such as a town, with a radius of 10km. It should prevent users from dragging or creating new mark ...

Trigger a jQuery click event to open a new tab

On a public view of my site, there is a specific link that can only be accessed by authenticated users. When an anonymous user clicks on this link, they are prompted to log in through a popup modal. To keep track of the clicked link, I store its ID and inc ...

Switch between class and slider photos

I am currently having an issue toggling the class. Here is the code I am working with: http://jsfiddle.net/h1x52v5b/2/ The problem arises when trying to remove a class from the first child of Ul. I initially set it up like this: var len=titles.length, ...

What is the best way to obtain the output produced by a function when a button is clicked

When I click on a button, the desired action is to trigger a function that adds a new property inside an object within a large array of multiple objects. This function then eventually returns a new array. How can I access and utilize this new array? I am ...

Angular.js - index template fails to execute controller, but other templates work flawlessly

I am facing a strange issue with my Angular application that uses ngRoute. I have set up different controllers for each template in the routes.js file: routes.js: angular.module('PokeApp', ['ngRoute']) .config(function($routeProvide ...

Using props in the v-bind:src directive with Vue - a comprehensive guide!

I have a Vue application with a Block component that needs to display an image. The Block component is used multiple times in the App component, each time passing a value to determine which image src to choose from an array. When I try to print {{ this.Im ...

Deleting tasks from the to-do list using Node.js and Express with EJS

Looking to implement functionality where each list item can be removed from a Node.js array by clicking on an HTML button using EJS and Express: I am considering placing an HTML button next to each list element so that the selected element can be removed ...

Issue with Snackbar slide transition not functioning properly in mui 5

Transitioning from material-ui 4 to mui 5 has presented me with a challenge. Whenever I try to display my snackbar, an error pops up in the console. After some investigation, I realized that the issue lies within the Slide component that I'm using as ...

Error in AngularJS when attempting to use an expression as a parameter for a function, resulting in a syntax parse

Encountering an issue while attempting to parse this code snippet. I need to pass an expression as a parameter in the ng-click function, but it's not allowing me to do so. If I don't use an expression, then clicking on the album image will clear ...

Leveraging the useContext and useReducer hooks within NextJS, while encountering the scenario of reading null

Trying to develop a tic-tac-toe game in NextJS and setting up a board context for my components to access. However, after integrating a reducer into the Wrapper to handle a more complex state, I'm encountering a null error. Errors: TypeError: Cannot r ...