Find numbers below 100 in an array containing a mix of numbers and strings using Javascript

Looking for a way to create a function that will return a number under 100? Check out the code snippet below:

const myArray = ['hello', 3, true, 18, 10,, 99 'ten', false]

const isLessThan100 = (array) => {
  // Insert solution here
}

I believe the filter method might be useful in this case, but unsure on how to specifically filter for a number less than 100 and not a string.

Any help would be greatly appreciated!

Answer №1

To determine if a value is a number, you can use the following method:

const myArray = ['hello', 3, true, 18, 10, 99, 'ten', false];

const lessThan100 = myArray.filter(item => {
  return (typeof item === "number") && item < 100;
});

Answer №2

Check out this concise example utilizing the filter method:

const myArray = ['hello', 3, true, 18, 10, 99, 101, 'ten', false];

const numbersLessThan100 = a => a.filter(e => +e === e && e < 100);

console.log(numbersLessThan100(myArray));

Answer №3

The typeof operator is used to determine the type of the operand without evaluating it.

Before checking if an item is a number and less than 100, you can first use the typeof operator.

To shorten the code, you can write it in a single line by omitting the curly braces.

Consider using Array.prototype.filter() like this:

const myArray = ['hello', 3, true, 18, 10,, 99, 'ten', false]

const isLessThan100 = (array) => array.filter(num => typeof(num) === "number" && num < 100);

console.log(isLessThan100(myArray))
const isLessThan100 = (array)

Answer №4

When looking to retrieve a single value from an array, considering reducing the array may be beneficial.

const
    array = ['hello', 3, true, 18, 10,, 99, 'ten', false],
    findValueLessThan100 = array => array.reduce((result, value) =>
        typeof value === 'number' && value < 100 && (typeof result !== 'number' || value > result)
            ? value
            : result,
        undefined);

console.log(findValueLessThan100(array));

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

Encountering the "ENOTFOUND error" when trying to install ReactJs via Npm

Struggling to install ReactJs? If you've already installed Nodejs and attempted to create a ReactJs project folder using npx create-react-app my-app, but encountered the following error: npm ERR! code ENOTFOUND npm ERR! syscall getaddrinfo npm ERR! er ...

What could be causing a functional component's child component to be using stale props?

I am currently working with Next JS, but the process is similar. I have refined the code and eliminated irrelevant parts. My goal is to create a form where new fields (child components) can be added dynamically. The default setting will be 1 field, with a ...

Error message: "Typescript is unable to locate offscreencanvas"

Currently, I am in the process of migrating a Three.js project to TypeScript. However, when attempting to compile it, I encountered an error which is documented in this particular issue on the Three.js repository: https://github.com/mrdoob/three.js/issues ...

Implementing the [] operator overload in a template class to retrieve objects from an array

template <class T> class Planer{ T array; int max_entries; int num_entries; public: Planer() { max_entries = 100; array = new T[max_entries]; num_entries = 0; } ~Pl ...

The issue lies with the Cookies.get function, as the Typescript narrowing feature does not

Struggling with types in TypeScript while trying to parse a cookie item using js-cookie: // the item 'number' contains a javascript number (ex:5) let n:number if(typeof Cookies.get('number')!== 'undefined'){ n = JSON.pars ...

The call stack limit has been exceeded due to the combination of Node, Express, Angular, and Angular-route

Embarking on a new SPA journey, my tech stack includes: Back-end: NodeJS + Express Front-end: Angular + Angular-route. Twitter Bootstrap Underscore Having followed many tutorials with similar stacks, my project files are structured as follows: pac ...

Verify if any column within a JSON object has a value of undefined, null, or is empty

Hey there, I'm a newcomer here and couldn't find any information on this topic after searching. Is there a method to scan a JSON object for empty values? For example, is there something like if(json[randomInt()].hasBlanks) that can be used? Or d ...

What is the method for including an input field beside the y-axis label in Chart.js?

I'm struggling to implement a live poll using Chart.js where users can select their option by checking a checkbox next to the y-axis label. My initial attempt was unsuccessful as placing the input boxes outside of the canvas led to alignment issues wi ...

Configuring delay time for dependencies in grunt

I have been encountering load timeout errors with Require in my application. I am using grunt to build my require files and the require optimizer. I have set a waitseconds parameter and it has resolved the timeouts issue on my local environment, but the pr ...

What is the best way to show translated messages using i18next when displaying JavaScript alerts?

We are in the process of developing an application that makes use of html/css/js, incorporating i18next for displaying translated strings. To display these translations, I insert an attribute within a tag. Here's an example: <a href="#top" id="ag ...

Can jQuery and Google Analytics be loaded together in a single process?

My current setup includes the following: <script src="http://www.google.com/jsapi?key=..." type="text/javascript"></script> <script> //<![CDATA[ google.load('jquery', '1.6'); //]]> </script> &l ...

Establish a connection with an existing web driver using Selenium in JavaScript

While I don't claim to be a Selenium expert, there may be something important that I'm overlooking in this situation. One of the software within the company initiates Google Chrome using ChromeDriver. I aim to link up with this browser through ...

I am encountering an issue in Nextjs with mongoose where it seems that the function mongoose.model() is not

In my E-commerce app built with Next.js and utilizing Mongoose, I defined a productSchema (models/Product) like this: const mongoose = require("mongoose"); const productSchema = new mongoose.Schema( { title: { type: String, required: true } ...

Convert a multi-dimensional array into a "flat" structure while preserving array keys and values

I have a complex array structure with X number of dimensions. Here is an example of the array: Array ( [system] => Array ( [step_x_y] => Array ( [0] => Schnitt %1 von %2 [1] => Trin %1 af ...

What is the best way to incorporate a description box for each city on the svg map that appears when you hover your mouse over it?

I am looking to display detailed descriptions for each city in the same consistent location on my map. With multiple pieces of information to include for each city, I want to ensure that the description box is positioned at the bottom of the map. Can any ...

Struggling to locate a route for the React styled components image

I'm having trouble locating the correct path for the image in my React styled components. I believe the path is correct, but could the issue be related to styled-components? Check it out here import styled from "styled-components"; export defaul ...

Enhance Vuetify functionality using TypeScript for custom components

I'm facing a challenge with extending a Vuetify component and setting default props in TypeScript. While I had success doing this in JavaScript, I am struggling to do the same in TS. Below is an example of how the Component was implemented in JS: imp ...

Manipulating the display style of an element without using jQuery

Could anyone assist me with this issue? I am currently facing a challenge in making the following script functional. It is intended to hide the button after it has been clicked. The script is being called through Ajax and PHP, so I am unable to utilize jQ ...

developing various instances of an object's characteristic

I'm currently attempting to create multiple versions of an object that includes an init function. I've experimented with using the 'new' function in JavaScript, but unfortunately it doesn't seem to work in this scenario as the cons ...

Is it possible to deselect a jQuery checkbox while keeping the other checkboxes checked and their results accessible?

Once the "ALL GAMES" checkbox is unchecked in the provided link, all results disappear, even though there are still checkboxes selected with the relevant list items to display. I am attempting to prevent all results from being removed when deselecting the ...