An empty array should be returned if a blank string is provided as input

While I've tackled similar exercises in the past and always managed to solve them, this time I'm facing a roadblock with something quite simple. I'm working on creating a function that retrieves the middle characters from each word in a string (if the word is of even length then you should find the middle two characters) and most of my code seems fine, except for when an empty string is passed as input.

This is how my code looks right now:

function getMiddleChars (str) {
 let emptyArray = [];
 let middleIndex = str.length / 2;
 for(let i = 0; i < str.length; i++) {
  if(str === "") {
    return emptyArray;
  } else if(str.length % 2 == 0){
     return str.slice(middleIndex -1, middleIndex + 1);
   }
 }
 return str.charAt(middleIndex);
}
// It should return [] when passed an empty string:
// AssertionError: expected '' to deeply equal []

I could really use some assistance here. Any help would be greatly appreciated. Thank you!

UPDATE:

function getMiddleChars (str) {
 let solution = [];
 let middleIndex = str.length / 2;
 if(str === ""){
   return [];
 } 
 if(str.length % 2 === 0){
   return solution.push(str.slice(middleIndex - 1, middleIndex + 1));
 } else {
   return solution.push(str.charAt(middleIndex));
 }
}

Even with the modifications, it's still not functioning correctly. I was confident I could crack this puzzle, but now I feel completely lost.

Answer №1

Divide the input string into individual words, then use Array.map() to iterate through each word and extract the middle characters:

function getMiddleChars(str) {
  return str ? str.split(/\s+/).map((word) => {
    const middle = (word.length - 1) / 2;

    return word.substring(Math.floor(middle), Math.ceil(middle) + 1);
  }) : [];
}

console.log(getMiddleChars('cats')); // ["a", "t"]
console.log(getMiddleChars('cat')); // ["a"]
console.log(getMiddleChars('a')); // ["a"]
console.log(getMiddleChars('hello world')); // ["l", 'r']
console.log(getMiddleChars('')); // []

Answer №2

The initial action in your function could involve the following:

if(string === "")
{
    return [];
}

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

ReactJs - SyntaxError: The JSX content is not properly terminated

I'm just starting out with ReactJs and have come across an issue that I can't seem to figure out. Here's my code snippet: var ListComponent = React.createClass({ render: function() { return ( <li>{this.props.va ...

"Removing an item from an array stored in localstorage: A step-by-step guide

I need to remove an object from an array and also delete it from local storage. I have attempted to use the splice method but am struggling with how to implement it correctly. Below is the code that I have tried: var details = []; function addEntry() ...

Utilizing localstorage data in angular 2: A comprehensive guide

Is there a way to utilize data stored in localstorage for another component? This is what the localstorage service looks like: localStorage.setItem('currentUser', JSON.stringify({ username: username, token: success, res: res.data })); I am inte ...

"Enhancing Progress Using JQuery Looping for Dynamic Progress

I am trying to create a progress bar that runs in a loop. It should count down to zero and then start again with the initial value. Check out this example on JSFiddle This is the JavaScript code: <script type='text/javascript'>//<![CD ...

Single-use condition for checkbox functionality in JavaScript

As a newcomer to javascript programming, I am struggling to make a checkbox display two radio buttons only when it is unchecked, even after researching solutions. Here is my current code snippet: <span><strong>Not Available</strong></ ...

An introduction to integrating Paged.js with Vue.js3

index.html <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <link rel="icon" type="image/svg+xml" href="/vite.svg" /> < ...

Incorporate dynamic variables into your HTML code using jQuery or JavaScript

I'm struggling to generate HTML code from JavaScript/jQuery within an HTML template rendered in Django. I need to append HTML code and also insert some values in between. Currently, I am using a basic string append method like this: var features =[&ap ...

Steps for deleting an element from a two-dimensional array

Whenever a new tic tac toe game is started, I encounter an issue with my 2D array. I have a method that loops through the array and sets all elements to Zero, but this approach does not achieve the desired outcome of having empty or null elements again. p ...

Developing a TypeScript library through modular class implementation

I have developed a Web API and now I want to streamline my code by creating a library that can be reused in any new project I create that interacts with this API. My goal is to organize my code efficiently, so I plan to have separate classes for each endp ...

Angular 2 FileReader: A comprehensive guide

I have a situation where I need to upload an image in section X and pass the base 64 data of the uploaded image to section Y. But I am encountering some difficulties in section X HTML: <input type="file" id="hotspot" (change)="uploadHotSpot($event)"&g ...

Modifying the status using retrieved JSON information

My goal is to retrieve data from an external API and use it to update the state of my app. Although I can see the data in the console, the state of my app remains unchanged when I try to run setState. class App extends Component { state={ jobs:[] ...

What is the best way to assign a value to a Vue component instance?

I am trying to send a value from my web component to the Vue instance and then use it in a Rails html.erb file. The element where I am mounting the Vue instance is shown below: <div id="app" :purchaseId="1"> However, I have b ...

PHP and AJAX: Combining Powers to Fetch Data

Greetings. I am currently in the process of creating a WordPress plugin that will manually send an email containing WooCommerce Order details to a specified supplier's email address. I am facing a challenge in understanding how to load data when a use ...

Generating a new object using an existing one in Typescript

I received a service response containing the following object: let contentArray = { "errorMessages":[ ], "output":[ { "id":1, "excecuteDate":"2022-02-04T13:34:20" ...

Activate the textbox without utilizing `.focus()` method

I am encountering an issue with a small iframe on my page. The content within the iframe is larger than the window itself, requiring users to scroll around to view it in its entirety. Within this iframe, there is a button that, when clicked, triggers an an ...

What is the most effective approach for incorporating a constants value within a component in react.js?

If a child component needs to access a globally set constant, such as the specific booking time range (e.g. SESSION_RANGE = [9, 17]), it should be parsed into a function (sessionCreator) first. The child component actually accepts an array of objects calle ...

Is there a way to convert a 2D array into a 3D array using Python?

I am attempting to visualize a two-dimensional array representing a pyramid in three-dimensional space. I could easily achieve this using the mesh() function in Matlab, but I am struggling to do it in Python. import numpy as np import matplotlib.pyplot a ...

Using the onclick event in JavaScript to create transition effects for swapping images

I am working on a website where I display 3 images. Instead of redirecting the users to a new page, I want to keep them on the same page. Question: How can I implement a functionality where clicking a <button> will display 3 new images in the view w ...

Is there a way to click on a button and have its background color change randomly each time?

I am facing an issue with a button on my HTML page. When the button is clicked, I want its background color to change to a random different color. However, despite trying various sources, I am unable to get it right. It seems like I am not placing the code ...

Accepts numerical values and a single comma

Is there a way to restrict an input field to accept only numbers and exactly one comma? Here's the approach I've been using: $("#my-field").on("keyup", checkKey); function checkKey() { this.value = this.value.replace(/[^0-9,]/g, ""); } ...