Output solely the values that are divisible by two

The Challenge: Develop a program that requests a series of numbers, separated by spaces. The objective is to generate a new list with only the even numbers from the input.

To achieve this task, convert the input into an array. While many programming languages offer built-in functions for this type of conversion, create your own algorithm without relying on these pre-existing features. Encapsulate the logic in a function named "filterEvenNumbers" which accepts the original array as input and outputs the new array containing only the even numbers.

Some additional points to consider:

//global array
    var arr = [];

    var arr = prompt("Enter your numbers");
    // var eachNumber = arr.split(",");
    var res = arr.split("");        
    console.log(arr);
    console.log(res);


    if(res = )

    // var str = "How are you doing today?";

    //push elements into array
    // arr.push(prompt("Enter in a bunch of numbers", "")); //push input to array
    // console.log(arr);

    // https://stackoverflow.com/questions/28252888/javascript-how-to-save-prompt-input-into-array
    // var arr = prompt("Enter your numbers").split(",");
    // console.log(arr);
    // var arr = [];
    // for(var i = 0; i < 10; i++)
    // arr.push(prompt("Enter a number");




    // Convert number into array in Javascript
    // https://stackoverflow.com/questions/20730360/convert-number-into-array-in-javascript
    // var numbers = "1, 2, 3";
    // var eachNumber = numbers.split(",");
    // /* now parse them or whatso ever */
    // console.log(eachNumber);   

Answer №1

let numbers = [1, 3, 5, 7, 9, 11, 13, 15, 17, 19],
evenNumbers = [];

for (let j = 0; j < numbers.length; ++j) { 
if ((numbers[j] % 2) === 0) {
    evenNumbers.push(numbers[j]);
}
}

This code snippet demonstrates how to filter out and collect the even numbers from an array into a separate array. You can easily modify it to display or manipulate the even numbers instead of storing them in another array. It provides a simple solution for organizing data effectively.

Answer №2

Are there any aspects of the question that are unclear to you? What specifically are you struggling with?

If you need to ask the user for input, you can utilize the

window.prompt('Enter a list of numbers separated by spaces');
method. This method will provide you with a string containing the user's input. To convert this string into a list without using built-in functions, consider the following approach:

  1. Save the user's input in a variable.
  2. Go through each character in the string. Maintain a variable called currentInteger to store the digits of the current number being evaluated (remember: numbers might consist of more than one digit, so as you iterate through the string, the current number may not be represented by a single character).
  3. When you encounter a space, it indicates that the currentInteger has been completed. Add it to a new list if it is an even integer.

Since the currentInteger variable is a string, use parseInt() to convert it to a number and verify if it is even.

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

CSS3 transition jQuery function with browser compatibility and customizable variables

Why is this code not working as expected? I have noticed that it only functions correctly on Chrome when I remove all vendors except for webkit. Interestingly, I have tried a similar example using the 'transform' property with the same method and ...

Troubleshoot Nested Array URL Parameter Problems in Node.js

I am encountering an issue with extracting data from an array that I am sending to my API through an AXIOS call to Express. The call is sent successfully, but the issue arises when trying to access the data in the property_features parameter. Even though m ...

Is it possible for me to manage events while executing Selenium tests?

Being new to Selenium, I am a JavaScript programmer interested in handling JavaScript events within my Selenium-2 tests (JUnit). Upon joining a team that already has existing tests with "waitForSomethingToBeRendered" methods, I am curious if there is a way ...

Personalized labels for your JQuery Mobile sliders

Struggling to make this work correctly, I aim to introduce tick marks and custom labels into jQuery Mobile's slider widget. My goal is to add tick markers at 0, 25, 50, 75, and 100 with a unique string above each tick. Additionally, I want these label ...

Issue with 'firebase.auth is not defined' error following SDK update

I've been using the Firebase JS sdk for web development without any issues for a year now. However, after recently updating my code from version 5.3.1 to the latest 6.5.0 SDK version, I encountered the following error: TypeError: firebase.auth is no ...

Guide on choosing the filename for downloads in Front-End applications

UPDATE: Creating a Blob from a base64 string in JavaScript I'm currently working on a feature where a user can click a button to download a file from its DataURL. However, due to Chrome restrictions on building <a> links, I encountered an err ...

Assigning numerical ratings to a web-based questionnaire in HTML

In my questionnaire, I have radio buttons and checkboxes that need to be graded. The format of the input elements looks like this: <input type="radio" name="1" value="Yes" onclick="document.getElementById('pls').setAttribute('requi ...

Issue with jQuery Ajax file upload in CodeIgniter

I am attempting to use AJAX to upload a file in the CodeIgniter framework, but I encountered an error message stating 'You did not select a file to upload.' Please review this code: View <form method="POST" action="" enctype="multipart/form- ...

What is the best way to attach an EventListener to all DOM elements with a particular class?

Within my DOM, I have dynamically created spans that all have the class "foo". Utilizing TypeScript, I aim to attach an onClick event to each of these spans post-creation. Here is my current approach: var foos = document.body.querySelectorAll(".foo"); f ...

How come I am unable to access a local JSON file using AngularJS $http?

I've been attempting to load a local file (todo.json) located in the same directory as my webpage using the following line of code: $http.get("todo.json").success( function( data ){ //Do Some logic}); However, when I try to do so, I encounter the fo ...

The Runtime Error encountered in NEXTJS: TypeError - Unable to iterate over 'games' as it is not

Attempting to create my inaugural website that showcases data from an API sans a tutorial. Does it seem like I may have overlooked something? I've successfully fetched the API and confirmed in the console log that the necessary data is present. Howev ...

What is the method to retrieve the value of a JSON object when the key matches the value of another JSON object?

Looking to expand my knowledge in javascript with an interesting challenge. Is there a way to retrieve the value of an object using another object's value as the key? For example: Obj1 = {"name":"John", "age":30, "car":null}; Obj2 = {"John":{"count ...

Tips for crafting a successful form success message within a bootstrap modal

RESOLVED After a long struggle, I finally managed to solve the issue using AJAX. However, in order to make it work, I had to remove WordPress and plan on re-uploading it in a separate directory later. Thankfully, this workaround does not affect my index p ...

Retrieving android array data from an in-app file

I've been wracking my brain trying to figure this out. I'm working on developing a block-based game with a 3x3 grid of blocks on the screen, each block having an associated int value to identify its type: int[][] blocksArray = { { 0, 0, 0 }, ...

Exploring the potential of utilizing the "wait" function in Selenium WebDriver for

I want to automate a test on my website using the Selenium WebDriver for JavaScript. How can I approach running tests here with content that may not be ready when the page loads, such as data coming from an external API? In my case, the content is loaded ...

The issue with JSON and asynchronous JavaScript requests

I've been trying to work on this for hours, but I can't seem to figure it out by myself. For a project, I need to use JSON, and even though I was able to make it work, the data is not being returned to the correct JSP; instead, it's just di ...

Ways to identify when text wraps to the next line

I'm working on a navigation menu (.navigation) that I want to hide instead of wrapping onto the next line when the screen width is small. I've been trying to figure out how to use javascript/jQuery to detect when wrapping occurs and hide the navi ...

Sending a cookie token to the server through the header

This is my first attempt at working with a server Utilizing React and express Storing token in browser cookie from the server //Upon login request res.cookie('token', token, {maxAge: 3600000} ).json({ user: userDoc, message: 'message!&apos ...

Cloning a file input does not retain the uploaded file in the cloned input. Only the original input retains the uploaded file

Whenever I duplicate an input type file, I encounter an issue where the uploaded file from the duplicated input is also linked to the original input. It seems like the duplicate input is somehow connected to and taking files for the original one. This is ...

What is the best method for importing Bootstrap into SvelteKit?

I am currently working on a SvelteKit website. I have integrated Bootstrap 5 into my project by adding it to the app.html file provided by the SvelteKit Skeleton starter project: <!-- Bootstrap styles and javascript --> <link rel="stylesheet ...