Guide on creating a function that accepts an Array of strings as a parameter and displays the initial letter of each element individually on separate lines

I am currently tackling my initial JavaScript assignment which involves the task of creating a function that accepts an array of strings as its parameter and outputs the first letter of each element individually on separate lines. The unique requirement is to utilize a FOR OF loop, function, and charAt() method for this task. The expected output should be: H, W, T, I, M, S; with each letter appearing on a distinct line. My struggle lies in understanding how to achieve this without resorting to using the toString.charAt method, as specified by the instructions. Moreover, I am uncertain about whether the FOR OF loop should contain the function or if the function should encompass the loop. Having commenced learning JavaScript just last week, I find myself quite perplexed. Any guidance offered would be greatly appreciated.

let arr = (["Hello", "World", "This", "Is", "My", "String"]);
//  mandatory use of for of
for (let element of arr) {
    console.log(element.toString())
}
 

 
// necessary function
let myFunction = (element) => element.charAt(0);

 myFunction(arr)
 

// required charAt
var str = new String( "This is string" );

        
         console.log( arr.toString().charAt(0));
         console.log(  arr.toString().charAt(6));
         console.log(  arr.toString().charAt(12));
         console.log(  arr.toString().charAt(17));
         console.log(  arr.toString().charAt(20));
         console.log( arr.toString().charAt(23));

Answer №1

For each iteration, utilize this expression:

// Consider using this code within a loop:
word.toString().charAt(0)+'\n'

Detailed instructions can be found in the example below

let hwtims = ["Hello", "World", "This", "Is", "My", "String"];
/*
Create a new string before looping: let char = ''
Append to char during each iteration: +=
Retrieve the first character of every
word: .toString().charAt(0)
Include a line break: +'\n'
*/
const firstChar = array => {
  let char = '';
  for (let word of array) {
    char += word.toString().charAt(0) + '\n';
  }
  return char;
};

console.log(firstChar(hwtims));

Answer №2

Take a look at these four examples below, the first one is your response, all involving loops.

let arr = (["Hello", "World", "This", "Is", "My", "String"]);

let myFunction = element => console.log(element.charAt(0));

console.log('\nfor of mode');
for (const iterator of arr) {
    myFunction(iterator);
}

console.log('\nfor each mode');
arr.forEach(element => {
    myFunction(element);
});

console.log('\nfor each mode2');
arr.forEach( el => myFunction(el) );

console.log('\nfor mode');
for (let index = 0; index < arr.length; index++) {
    const element = arr[index];
    myFunction(element);   
}

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

I am looking for the best way to sort my JSON data based on user roles before it is transmitted to the front end using Express and MongoDB. Any

I scoured the internet high and low, but to no avail - I couldn't find any framework or code snippet that could assist me in my predicament. Here's what I'm trying to achieve: whenever a response is sent to my front-end, I want to filter th ...

Devising a method to display configurable products as related items along with their customizable options in Magento

I am in the process of creating an e-commerce website using Magento for a client. The issue I am facing is that when I include a configurable product as a related item, it displays the product but without a checkbox. From what I have researched, Magento do ...

What are some ways to conceal methods within a class so that they are not accessible outside of the constructor

I am a newcomer to classes and I have written the following code: class BoardTypeResponse { created_on: string; name: string; threads: string[]; updated_on: string; _id: string; delete_password: string; loading: BoardLoadingType; error: Bo ...

Transitioning between modals using Tabler/Bootstrap components in a ReactJS environment

Currently, I am constructing a Tabler dashboard and incorporating some ReactJS components into it. Initially, I used traditional HTML pages along with Jinja2 templates. However, I have now started integrating ReactJS for certain components. I prefer not t ...

Using iTextSharp in .Net to convert the action result into a downloadable pdf file via ajax

I have been successfully using iTextSharp to convert a razor view into a downloadable PDF via a C# controller. While the current implementation is functioning perfectly, I am seeking a way to transmit a model from a view to the PDF controller and enable th ...

Retrieve returned data using jQuery

How can I retrieve data when using the jQuery.get method? function send_data(pgId) { for(var i = 0; i < pgId.length; i++) { // $.get(url, data, success(data, textStatus, jqXHR)) $.get('index.php?page=' + pgId[i], pgId[ ...

"Error: The chai testing method appears to be improperly defined and is not

I am trying to set up a Mocha and Chai test. Here is my class, myClass.js: export default class Myclass { constructor() {} sayhello() { return 'hello'; }; } Along with a test file, test.myclass.js: I am attempting to a ...

Steps for choosing an option in MUI select list using jest

I am looking for a way to automate tests for a Material UI select component using Jest. Is there a way to select an option from the list of options in the Material UI component and confirm that its value has been successfully populated in Jest? I have se ...

Copy values of multiple input fields to clipboard on click

I have a collection of buttons in my Library, each with different text that I want to copy when clicked function copyTextToClipboard(id) { var textElement = document.getElementById(id); textElement.select(); navigator.clipboard.writeText(textElement. ...

Diminish, then lead to a fresh page

I have encountered an issue with my code. The wrapper performs a fade out effect before redirecting the user to a URL. However, it only fades out once and I suspect this is due to the browser caching or loading the page quickly. Is there a way to ensure t ...

The ng-message function appears to be malfunctioning

I am facing an issue with the angularjs ng-message not working in my code snippet. You can view the code on JSfiddle <div ng-app="app" ng-controller="myctrl"> <form name="myform" novalidate> error: {{myform.definition.$error ...

Adding up values in a Hive array

I've come across the table below: user_id, items_x, items_y 1, [0, 1, 3, 0], [1, 0, 0, 1] 2, [1, 1, 1, 0], [1, 0, 0, 2] 3, [2, 1, 0, 0], [0, 0, 4, 0] My goal is to calculate the sum of elements in each array and display the results like this: u ...

Exploring logfile usage in JavaScript. What is the best way to structure the log?

Currently, I am developing a Python program that parses a file and records the changes made to it. However, I am facing a dilemma regarding the format in which this information should be saved for easy usage with JavaScript on the local machine. My objecti ...

Exploring Unicode Symbols for Icon Selection

I'm currently working on integrating an icon picker into my application that will enable the user to select a mathematical operator for data comparison. While I have successfully implemented the fontawesome-iconpicker on the page, I am encountering d ...

Retrieve data attributes to obtain details about the slider before and after

My task is to create a slider with information about the previous and next slides. For example, in the slider, there are left < and right > arrows. Behind these arrows, there are circles. When you hover over any arrow to change the next or previous ...

React component making repeated calls to my backend server

As a React newbie, I am currently in the process of learning and exploring the framework. I recently attempted to fetch a new Post using axios. However, upon hitting the '/getPost' URL, I noticed that the GetPost component continuously calls the ...

Building a hierarchical tree structure using arrays and objects with Lodash Js

I am attempting to create a tree-like structure using Lodash for arrays and objects. I have two arrays, one for categories and the other for products, both with a common key. The goal is to organize them into a tree structure using string indexing. let ca ...

Targeting an HTML form to the top frame

Currently, I have a homepage set up with two frames. (Yes, I am aware it's a frame and not an iFrame, but unfortunately, I cannot make any changes to it at this point, so I am in need of a solution for my question.) <frameset rows="130pt,*" frameb ...

One of the functionalities is not functioning properly: either the validation or the AJAX

My validation code was working fine until I added some ajax code. Now, when I include the onclick="return chk()" in the submit input field, the validation code stops working. But if I remove it, the ajax code doesn't work. How can I resolve this issue ...

Utilizing a mutual RxJS subject for seamless two-way data binding in Angular 2

I have a unique service dedicated to managing app configurations class Configuration { get setting() { return dataStore.fetchSetting(); } set setting(value) { dataStore.saveSetting(value); } } This configuration is linked to components t ...