Changing numbers in an array using JavaScript

I'm struggling to create an array containing 5 random numbers ranging from 1 to 100. My goal is to then identify the even numbers and, for any odd ones, increase them by 1.

For instance:

array = [7, 13, 2, 60, 93]

The desired result should be

modified_array = [8, 14, 2, 60, 94]
, unfortunately I can't seem to figure it out..

Any assistance in solving this problem would be greatly appreciated. Thank you!

const array = []
const modified_array = []
while (array.length < 5) {
  i = (Math.floor(Math.random() * 100) + 1);
  array.push(i);
  for (i in array);
  if (i % 2 !== 0) {
    modified_array.push(i)
  }
}

console.log("array");
console.log(array);
console.log("-------------------------")
console.log("modified_array");
console.log(modified_array);

Answer №1

Have you ever considered doubling the half-maximum value instead?

const array = [];
while (array.length < 5) {
    array.push(2 * (Math.floor(Math.random() * 50) + 1));
}

console.log(...array);

Answer №2

All you need is a single variable and a for loop to make this solution work seamlessly. Simply add the element to the array and then check if it is an even number. If not, just increase its value by 1.


for(let i = 0; i<5; i++) {
  array.push((Math.floor(Math.random() * 100) + 1))
  if(array[i] % 2 != 0) {
    array[i] += 1
  }
}

console.log(array)

Answer №3

Simply increment the current value by 1 if it is not an even number, otherwise keep the value unchanged and add it to the new array.

const array = []
const modified_array = []
while (array.length < 5) {
    i = (Math.floor(Math.random() * 100));
    array.push(i);
    if (i % 2 !== 0) {
        modified_array.push(i + 1);
    }else{
        modified_array.push(i);
    }
}

console.log(...array);
console.log(...modified_array);

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 calculator is not simply adding two numbers; instead, it is combining them together to display something like "2+2=22"

<title>Calculator</title> <script type="text/javascript"> function Calculate(){ var myWorker = document.getElementById('myOperation'); var numberOne= document.getElementById('firstNumber').value; ...

How to launch a document in a new tab using AngularJS?

LIVE DEMO When given the URI of a file, my goal is to open it in a new tab instead of a new window. It appears that using $window.open(uri, '_blank') is not an option. I attempted this workaround: var link = angular.element('<a ...

Is it possible to utilize "this" in mapMutations spread within Vue instance methods?

Trying to define Vuex mutations like this: export default { props: { store: String }, methods: { ...mapMutations({ changeModel: `${this.store}/changeModel` }) } } Encountering an error message: An er ...

Diving into Angular2 template forms: unraveling the mysteries of the reset function

After going through the template forms tutorial in Angular2, I'm facing a bit of confusion regarding the behavior of the native reset JavaScript function on Angular2 ngModel. While it's not explicitly clarified in the official documentation, my u ...

How to fix the issue of not being able to pass arguments to the mutate function in react-query when using typescript

Currently, I am exploring the use of react-query and axios to make a post request to the backend in order to register a user. However, I am encountering an error when attempting to trigger the mutation with arguments by clicking on the button. import React ...

Displaying Bootstrap Alert for a single occurrence

One issue I'm facing involves setting up alerts with Bootstrap. Initially, these alerts are hidden from view. However, when a rating is submitted using raty, an Ajax request is triggered. Upon successful completion of the request, an alert is displaye ...

Ways to retrieve information from every subcollection in Firestore

I am looking to retrieve information from all onsite collections https://i.sstatic.net/hnkW4.png My goal is to access data from all onsite collections. Here is the code I am using: export class FirebaseService { onsiteRef: AngularFirestoreCollection< ...

How to send an html form with php, store it in a MySQL Database, and utilize Ajax and jQuery for

As a beginner in PHP form creation, I have been exploring various tutorials and combining different techniques to create my form. However, I am facing challenges as none of the tutorials cover everything comprehensively from beginning to end. While I beli ...

Python automation with selenium - capturing webpage content

I am utilizing selenium to scrape multiple pages while refraining from using other frameworks such as scrapy due to the abundance of ajax action. My predicament lies in the fact that the content refreshes automatically nearly every second, especially finan ...

A guide on personalizing HTML for Django forms

I have implemented an HTML template on my website and need to capture information for my Django backend. Specifically, I am trying to extract the email address from this section of code: <input type="text" placeholder="Email" value="" style="height: 30 ...

Guide on converting a date input to a timestamp

I am trying to convert the date retrieved from an HTML5 date input into a timestamp and store it as a variable. HTML: <form> <section class="input"> <input type="date" id="date" name="maintenanace_date"/> </section> <sectio ...

What is preventing me from utilizing Jinja in JavaScript for a django website?

When using Python and Django framework for website development, one useful tool to incorporate is the jinja template engine. For instance: Rather than hard-coding an import like this: <script src="assets/js/onebutton.js"></script> We can do ...

Using JQuery to duplicate text and insert it into a textarea

Looking for a more efficient way to achieve the same functionality with my JavaScript function. Currently, it copies text from a hidden span and inserts it into a textarea on a website after a few clicks. Any ideas on how to streamline this process? It&apo ...

Updating Hidden Field Value to JSON Format Using jQuery and JavaScript

var jsonData = [{"Id":40,"Action":null,"Card":"0484"}]; $('#hidJson', window.parent.document).val(jsonData); alert($('#hidJson', window.parent.document).val()); // displays [object Object] alert($('#hidJson', window.parent.doc ...

What is the process for sending a selected option using AJAX?

Using Ajax within Laravel to save data involves a form with input fields and a select option. Here is the form structure: <form class="forms" method="get" action=""> {{ csrf_field() }} <div class="form-group row ...

Creating an Add-in using the Excel JavaScript API based on an already existing spreadsheet

Is there a way to create an Add-in using Excel JavaScript API from an existing spreadsheet? When running npm start, it generates a blank workbook. I believe changes need to be made in the Manifest.xml file, as npm start triggers office-addin-debugging star ...

Adding an onprogress listener to XMLHttpRequest.upload causes a bizarre issue where the POST data is halted from being transmitted. What's up

What exactly is happening? This piece of code is responsible for sending data via the POST request. I can tell because my Node server is receiving it in chunks. let req = new XMLHttpRequest(); req.onload = () => { console.log("Done"); }; req.open ...

Is it feasible for a JavaScript function to receive the innerHTML of the element from which it is invoked as an argument?

Is there a way to bind a function that takes a String as a parameter to a button so that it is called onclick and takes the innerHTML of the element as a parameter, without assigning the button an id or using queryselector? <button onclick="myFunct ...

Show the details of a location directly on Google Maps API marker

I am currently developing a project using AngularJs, where I am displaying information on a Google Maps interface. You can check out my example on this plunker link. My goal is to retrieve the 'city' and 'desc' fields by clicking on th ...

"Displaying slider position relative to total count before clicking on it for

Utilizing the Foundation Zurb 6/Orbit Slider. Is there a way to show the current slide count and total before the slidechange.zf.orbit event triggers? Should I integrate an event prior to this, on window load, or use another method? The first slide initi ...