What is the best way to uppercase each element in an array using only a while loop in plain ECMAScript 5?

Struggling with a simple exercise that requires converting names to uppercase and passing them to an empty array using only while loop(s) in plain JavaScript:

var names = ['rob', 'dwayne', 'james', 'larry', 'steve'];

var UpperCase = [];

An attempt was made using an object (with mistakes):

var change = {
  "mary":"MARY",
  "john":"JOHN",
  "james":"JAMES",
  "anna":"ANNA",
  "jack":"JACK",
  "jeremy":"JEREMY",
  "susanne":"SUSANNE",
  "caroline":"CAROLINE",
  "heidi":"HEIDI"
}
for(var key in change) {
  var obj = change[key];

  for (var prop in obj) {
  var value = obj[prop];
}
}

while(names[i]===change.key) {
  for(var i=0; i<names.length; i++) {
  UpperCase = change.value[i];
} }

Seeking assistance with this. Thanks!

Answer №1

Alternative to toUppercase():

To determine if a character is uppercase or lowercase, you can use the following code snippet:

str[i].charCodeAt(0) > 96

For more information on the charCodeAt function, check out this link.

If you are interested in fromCharCode function details, visit this page.

Using while loop efficiently:

var i = 0;
while (i < str.length) ...

Avoiding push function for arrays:

 UPPERCASE[UPPERCASE.length] = uppercase(names[i]);

I trust that this function will be beneficial for your needs.

function uppercase(str) {
  var i = 0;
  var output = "";
  while (i < str.length) {
    var x =
      (str[i].charCodeAt(0) > 96)
        ? String.fromCharCode(str[i].charCodeAt(0) - 32)
        : String.fromCharCode(str[i].charCodeAt(0));
    output += x;
    i++;
  }
  return output;
}

Example:

function uppercase(str) {
  var i = 0;
  var output = "";
  while (i < str.length) {
    var x =
      (str[i].charCodeAt(0) > 96) ?
      String.fromCharCode(str[i].charCodeAt(0) - 32) :
      String.fromCharCode(str[i].charCodeAt(0));
    output += x;
    i++;
  }
  return output;
}
var UPPERCASE = [];
var names = ["rOb", "dwayne", "james", "larry", "steve"];

var i = 0;

while (i < names.length) {
  UPPERCASE[UPPERCASE.length] = uppercase(names[i]);
  i++;
}

console.log(UPPERCASE);


Updated Version:

Solution without using a function and implementing linear condition technique.

var UPPERCASE = [];
var names = ["rOb", "dwayne", "james", "larry", "steve"];

var i = 0;

while (i < names.length) {
  var j = 0,
    output = "",
    str = names[i];
  while (j < str.length) {
    var x;
    if (str[j].charCodeAt(0) > 96) {
      x = String.fromCharCode(str[j].charCodeAt(0) - 32);
    } else {
      x = String.fromCharCode(str[j].charCodeAt(0));
    }
    output += x;
    j++;
  }
  UPPERCASE[UPPERCASE.length] = output;
  i++;
}

console.log(UPPERCASE);

Answer №2

To ensure your while loop stops at the appropriate time, you must create an increment (i). Although a for loop may be more suitable in this scenario, a while loop is also effective.

var names = ['rob', 'dwayne', 'james', 'larry', 'steve']
var i = 0
var result = []

while (i < names.length) {
  result.push(names[i].toUpperCase())
  i++ 
}

console.log(result)

Answer №3

To optimize your code, consider using a handler function within the map method:

var fruits = ['apple', 'banana', 'orange', 'kiwi', 'strawberry'];
var capitalizedFruits = fruits.map(function(item){ return item.toUpperCase() });

Answer №4

Expanding on @andrewgi's response:

let people = ['rob', 'dwayne', 'james', 'larry', 'steve']
let index = 0
let uppercaseNames = []

while (index < people.length) {
  uppercaseNames.push(people[index].toUpperCase())
  index++ 
}

console.log(uppercaseNames)

I eliminated the +1 addition after verifying the names.length and properly formatted the toUpperCase method using camel-case.

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

Obtain a masterpiece by creating a canvas in React

Greetings! I have developed a drawing app using react and I am looking for a way to capture what the user has drawn on the canvas when they release the mouse button. This process should repeat continuously until the user stops drawing. Can anyone suggest h ...

Create numerous collapsible elements using the ui.bootstrap and AngularJS frameworks

Currently, I am working on implementing the ui bootstrap collapse feature. The static single or double collapse system works perfectly fine, but for my specific design requirements, I need to create collapses using ng-repeat. Unfortunately, I am unsure how ...

What is the best way to manage a promise's response?

I'm currently facing a situation where I need to create a petition to an endpoint and retrieve the URL of the backend that I intend to use. My setup involves a file with the API configuration where I instantiate axios. Previously, my approach was sim ...

Is it possible to retrieve the `arguments` objects if one of the parameters is named "arguments"?

This code snippet will output 1: (function (params) { console.log(params); }(1, 2)); The params object has replaced the default arguments. Can we retrieve the original arguments object within the function's scope? ...

Displaying a tableview of images converted from an array of base64 strings

I am facing an issue with binding images in base 64 format from an array to a table view. I attempted using the code snippet below to convert base 64 strings to image: UIImage *image = [UIImage imageWithData:[NSData dataFromBase64String:result]]; Howeve ...

Arrange the last word in the array

I have an array example as shown below: array_store = ['01-42.0-19.5-100-26.25-46.94-D', '01-61.0-19.5-100-26.25-51.69-C', '36.0-1.0-100-25.0-40.5-D', '52.0-19.5-70-35.0-44.12-A'] I need to organize the elements in ...

How can I call a function from one Vue component in another component?

I have developed a component with the function "logout" as seen in the code snippet below: // @/component/Painel.vue <template></template> <script> export default { name: 'panel', methods: { logout: function () { ...

Embedding a countdown timer in basic HTML code

Attempting to embed the following into an HTML website: The issue I am facing is that when I run it, the timer does not appear. However, when I run it in fsFiddle, I do see the countdown timer. What could be causing this problem? <!DOCTYPE html> & ...

Activating the Mobile Menu Function when the Window is Resized

I've developed a JavaScript function that triggers on window resize. When switching between landscape and portrait orientation on mobile devices or tablets, the window dimensions change. This functionality is also useful for browser testing on desktop ...

What is the method for altering the background color of an input field upon entering text?

As a beginner in Javascript and jQuery, I am struggling to understand why my code is behaving the way it does. I have written two similar functions aimed at changing the background color of an input field. The objective is to set the background color of t ...

FoxyWeb Requests: Utilizing XMLHttpRequest in Firefox Extensions

While I've come across plenty of examples on how to create xhr requests from Firefox Add-ons, I'm currently exploring the new WebExtensions framework (where require and Components are undefined) and facing an issue with sending a simple XmlHttpRe ...

Show only the portion of the image where the cursor is currently hovering

Information in advance: You can check out the current code or view the live demo (hover image functionality not included) at . The concept: I would like to have it so that when I hover my cursor (displayed as a black circle) over the image, only the s ...

Tips for sending a form using Angular 1.5.8 and Java Servlet via POST method

After reading various tutorials and online documentation, I'm still struggling to figure out how to pass parameters from a JSP form. Below is the JavaScript script I am using: var app = angular.module('myApp', []); app.controller('Form ...

Ionic - numerical age selector control

Currently working on a hybrid mobile app and ran into a specific issue. I'm in the process of adding new items to my left side menu, including an age number spinner component (min:18, max:65). After searching through various sources and Ionic documen ...

Guide to crafting a custom asynchronous function in a separate file using Express JS

I have a specific function that I want to create called: my_function.js: module.exports = function(req, res, next){ var js_obj; // Do something with the JavaScript object above // Afterwards, I want to append "js_object" to the request object: req.js ...

Adding dynamically fetched JSON to an existing table

http://jsfiddle.net/mplungjan/LPGeV/ What could be improved in my approach to accessing the response data more elegantly? $.post('/echo/json/',{ "json": JSON.stringify({ "rows": [ { "cell1":"row 2 cell 1", "cel ...

Avoid typing the URL directly into the address bar to prevent redirection

For instance, if I have a domain (abc.com) with a page abc.com/data-list, how can I prevent users from manually typing in the address bar to access that page? I want to use JavaScript to dynamically update the content section without refreshing the entire ...

Tips for adjusting the font size according to the varying number of characters entered

I am currently facing a challenge with adjusting the font size based on the dynamic number of characters. For example, I have a set of characters with a font-size of 40px, and as more characters are added, the font size should decrease to fit within the av ...

What is the best approach for sending mapbox coordinates to a higher-level class in a react application?

As a beginner in learning React, I'm currently working on setting a map marker with a click event on a Mapbox GL map. The challenge I'm facing is passing the lngLat object back up to the parent component. Can someone guide me on how to achieve th ...

Encountering difficulties accessing props while invoking a component in React

In my project, I've created a component called FilterSliders using Material UI. Within this component, I passed a prop named {classes.title} by destructuring the props with const { classes }: any = this.props;. However, when I try to access this prop ...