Ways to determine if an array with a mix of data types includes string values

Challenge I'm Currently Tackling:

To solve this challenge, create a function named "findShortestWordAmongMixedElements".

The task is to find and return the shortest string from an array that contains mixed element types.

Important Notes:
* In case of ties, the function should return the first occurrence in the given array.
* The array will have values other than strings.
* If the array is empty, it should return an empty string.
* If there are no strings in the given array, it should return an empty string.

This is my current implementation:

function findShortestWordAmongMixedElements(array) {
  if (array.length === 0)) {
    return '';
  }
  var result = array.filter(function (value) {
    return typeof value === 'string';
  });
  var shortest = result.reduce(function (a, b) {
    return a.length <= b.length ? a : b;
  });
  return shortest;
}

var newArr = [ 4, 'two','one', 2, 'three'];

findShortestWordAmongMixedElements(newArr);
//returns 'two'

My code works fine except for passing the test where "no strings are present in the given array". Any hints on how to tackle this scenario or suggestions to optimize the function?

Answer №1

"I am able to make everything work except for passing the test that checks if there are no strings in the given array."

By utilizing the .filter() method, you can isolate only the strings in the array. If the resulting array is empty, then it indicates that there were no strings present. It seems like you already have the necessary code to check if an array is empty.

Answer №2

To achieve this functionality, you can utilize the reduce method along with an initial value such as null (or any other specific non-string value). The idea is to identify the shortest string within the array and if there are no strings present, the reduce function will return the initial value. In that case, we can modify it to return an empty string instead.

function findShortestString(arr) {
  return arr.reduce(function(acc, value) {
    if (typeof value === 'string') {
      if (acc === null || value.length < acc.length) {
        acc = value;
      }
    }
    return acc;
  }, null) || '';
}

var sample1 = [4, 'two', 'one', 2, 'three']; // Contains strings
var sample2 = [4, {}, [], 2, new Date()];     // No strings
var sample3 = [];                              // Empty array
var sample4 = [4, '', 'two', 2, 'three'];       // Strings with the shortest being empty

console.log('sample1: "' + findShortestString(sample1) + '"'); // "two"
console.log('sample2: "' + findShortestString(sample2) + '"'); // No strings found
console.log('sample3: "' + findShortestString(sample3) + '"'); // ""
console.log('sample4: "' + findShortestString(sample4) + '"'); // ""

This approach tends to be more efficient compared to using a combination of filter and reduce, as it only iterates over the array once.

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

What sets apart a void function from an int *function when it comes to returning arrays?

Is there a distinction in function return type when working with arrays passed by reference in the following two examples? int *swap (int *arr, int size) { // code return arr; } // OR void swap (int *arr, int size) { // code } ...

Whenever I anticipate receiving an array, Fetch always delivers a promise

I'm currently facing an issue with my simple API GET request. The array I need is always inside a promise and I can't figure out how to extract it or access the values stored within it. function getLocation(name) { let output = fetch(`http:// ...

How to validate text from a <span> tag using Selenium WebDriver and JavaScript

Is there a way to retrieve the value from the span tag using this code snippet? var error = driver.findElement(webdriver.By.id('error-container-text')).getAttribute('innerHTML'); When I run the above code, I get a response that looks ...

The art of blending different inheritance (Styled Elements)

Can components be based on other styled components? Take a look at the code snippets below. I am interested in creating a component like this: const HeaderDropDownLi = styled(DropDownLi, HeaderItem) Both DropDownLi and HeaderItem are derived from a style ...

Switch the value of a string within an array to a different string

I am facing the following situation: Collection {#296 ▼ #items: array:1318 [▼ 0 => {#289 ▼ +"Column1": "string1" +"Column2": "string2" +"Column3": "string3" +"Column4": "string4" +"Column5": "string5" } 1 => {#292 ▼ +"Column1": ...

Limiting the number of promises in AngularJS

My web application allows users to select multiple files using a file input. After the user selects the files, I upload them one by one through my REST API. However, in Internet Explorer, if the user selects more than 10 files at once, some of the requests ...

Deleting an added element upon closing the dialog box

Utilizing JQuery and Ajax, I successfully update my database. Following each update, a png icon is displayed briefly for 1 second. Specifically, the update form is contained within a JQuery dialog box. However, upon closing the dialog box after an update, ...

Unable to transmit form information using HTML/JavaScript/Express Node application

I'm facing a challenge in developing an app that allows me to input event information and then display it on a map. I'm encountering difficulties at the initial stage when it comes to saving the data. Even though Chrome's Inspect tool indica ...

Using PHP to generate JSON arrays from MySQL data for displaying in Highcharts

Need help with configuring Json output for my highchart scatter plot? Check out this example. Here is the desired Json output: [{ "name": "Female", "color": "red", "data": [{ "name": "Anna", "x": 161.2, ...

Implementing CSS styling within a JavaScript file

I have a vague memory of an easy way to incorporate CSS code within a JS file, but I can't recall the specific details. Simply inserting CSS code into a JS file doesn't seem to work, so there may be a need for comments or some other method. *No ...

Updating the status of a checkbox array within the reducer to reflect changes made in the user interface

I've implemented something similar in React: const CheckboxItems = (t) => [ { checked: true, value: 'itemsCancelled', id: 'checkBoxItemsCancelled', labelText: t('cancellations.checkBoxItemsCancelled&apos ...

Sorting functionality in Dyntable is not functioning properly when called from an Ajax request

I can't seem to get DynaTable with Ajax to work properly. Sorting, searching, and pagination are not functioning as expected. When I click on the column header, nothing changes in my table. Could someone please assist me? Below is my code snippet: H ...

Timeout feature for image slider in Angular JS

Hey there, I've been trying to get my AngularJS image slider to work like a slideshow where the images transition smoothly from slide to slide. I managed to code the functionality for navigating to the next and previous images, but when I attempted to ...

Mirror the image horizontally prior to saving

I'm working on a camera web app that has filters similar to Snapchat. I'm currently facing an issue where the image is mirrored because I'm using the front camera. Is there a way to flip the image before downloading it? Thank you for your re ...

Struggling to concentrate on a text field following navigation in an AngularJS application

My current project involves working with an AngularJS application where I am facing a challenge in setting the cursor or focus on a specific text box when routing to a page. Despite my attempts using various methods such as setFocus() in JavaScript, autofo ...

Ways to recycle the table feature in angular2?

I am new to Angular2 framework and I am looking to efficiently reuse a single table component across my entire application. However, I am encountering challenges when it comes to displaying arrays in the table rows. How can I iterate through any type of ar ...

React with TypeScript: The struggle of getting LocalStorage to work

Currently, I am dealing with persistence in a todo application developed using React and TypeScript. To achieve the desired persistence, I have implemented localStorage. Allow me to share some code snippets: const [todos, setTodos] = useState<todoMod ...

Problem with selecting and deselecting bus seat reservations accurately

I'm currently developing a bus booking application. To create the seat booking layout, I used Recyclerview and GridLayoutManager. The layout was created successfully with 4 seats in each row and 5 seats in the last row, resulting in a GridLayoutManage ...

Exploring the Interaction of Users with HTML Table Cell <td>

I am currently analyzing the code for a web page. Within this code, users have the ability to double-click on a cell in a table (<td> as shown below) and input a value. Is there a specific attribute or element within this HTML that indicates user in ...

Iterating over an object while omitting certain elements

Is there a way to insert a separator at a specific position in JSX? For example, I have a list that displays text when an item is clicked: https://i.sstatic.net/s71yE.png Here is the code: <Accordion> {items.map((item, index) => ( <Acco ...