Searching for a two-digit number in an array

I need to search for the Number 7 within an Array and return true regardless of whether it's 7, 47, or 507.

The Array in question is: [17, 23, 9, 590]

My initial attempt was to use arr.includes(7) but this method only returns the specific number 7. This results in a false output because there is no exact match for 7 in the Array - only 17.

Answer №1

The issue lies in the comparison number === 7, it is recommended to compare each individual digit instead.

To do this, you can utilize the Array.prototype.some function along with the String.prototype.includes function to search for a specific digit or character.

This method successfully identifies the number 7 within each number's digits.

console.log([17, 23, 9, 590].some(n => String(n).includes(7)))

Answer №2

To analyze the numbers, consider combining them and checking if the digit 7 is present.

var numbers = [17, 23, 9, 590],
    includesSeven = numbers.join('').includes(7);

console.log(includesSeven);

Answer №3

Is it possible to find the number that when divided by 10 has a remainder of 7?

const findByLeastSigFig = (arr, n) => arr.find(x => x % 10 === n);

console.log(findByLeastSigFig([17, 23, 9, 590], 7));

Answer №4

To determine if the number 7 only appears in the last position, you can perform division by 10 and check the remainder.

const numbers = [7, 9, 17, 23, 57, 407, 590];
const filteredNumbers = numbers.filter(num => num % 10 === 7)
console.log(filteredNumbers)

Answer №5

When faced with this problem, there are multiple correct solutions available to choose from. One of the most straightforward and efficient approaches is to utilize the Array.prototype.toString() method. This method concatenates the elements of the array into a single string, with each element separated by commas. For example, [17, 23, 9, 590].toString() will result in the string "17,23,9,590". To then locate the index of the number 7 within this string, you can employ the String.prototype.indexOf() method, which will return either the 0-based index of the search value or -1 if the value is not found.

In summary, the following line of code accomplishes these tasks:

console.log([17, 23, 9, 590].toString().indexOf(7) != -1);

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

transferring id values between controllers in angularJS

How can I pass an id from one controller to another in Angular? I have a select menu that allows for selecting a tournament, and upon selection, I want to retrieve the tournament’s _id value in a different controller to query data. Being new to Angular ...

React Native with MobX: Due to the enabled strict mode, it is not permitted to change observed observable values without utilizing an action

I've been experiencing an issue with mobx in my react-native app where I receive a warning when trying to make changes to an array of ids. Here's the code snippet causing the problem: let copyy = userStore.unreadChatIds; copyy.push(e.message.chat ...

Printing array elements in reverse order

Trying to debug my program, I need to print out all elements in the array. This is the loop for printing all elements of the array: for(int i = 0; i <= 9; i++) { printf("Words: %s\n", &words[i]); } In a header file, there's ...

A guide on aligning an object with the cursor position

In a 'open world' game setting, I have a simple sword image drawn pointing up, where the player can freely move around the world to all coordinates. My goal is to make the sword point towards the mouse cursor. One of the challenges I'm faci ...

What are the steps to clear a client's local cache after updating my website?

Is there a simple way to clear the cache of all players who have previously played my game? The game stats are stored in local storage, and some players experienced bugs when the stats were incorrect. This outdated data is now affecting the updated stats ...

Ensure that an element exists in Selenium before proceeding with actions

Currently, I am undergoing testing with the Selenium web driver and one of the requirements is to wait for my object to be defined on the page. Important: There are no visible changes in the DOM to indicate when my object is ready, and it's not feasib ...

Modification to the scope are not being displayed accurately on the modal user interface

I have a disabled button that needs to be enabled after a certain amount of time. My attempt at using $timeout and ng-disabled is not producing the desired result. Here is the HTML code: <button id="resend_button" class="btn btn-block btn-info" ng-cl ...

Unable to display elements from an array in the dropdown menu generated by v-for

Having just started learning Vue.js, I am facing a challenge in rendering the following array: countries: ["US", "UK", "EU" ] I want to display this array in a select menu: <select> <option disabled value="">Your Country</option& ...

Using jQuery to access the value of the CSS property "margin-left"

I created a JavaScript game with moving divs that have different transition times. The game includes a function that is called every 1/100 seconds, which checks the position of the divs using: $("class1").css("margin-left") Here's the strange part: ...

Tips for using ng-repeat in AngularJs to filter (key, value) pairs

I am trying to achieve the following: <div ng-controller="TestCtrl"> <div ng-repeat="(k,v) in items | filter:hasSecurityId"> {{k}} {{v.pos}} </div> </div> Code snippet for AngularJs: function TestCtrl($scope) { ...

Would it be feasible to rename files uploaded to Firebase within an AngularJS controller using logic?

Is there a way to apply regex to rename uploaded files before saving them to firebase storage? It seems that firebase file metadata does not support this function. I am currently using angularjs and would appreciate any guidance on this matter. ...

Window displaying multiple product options

Having an issue creating modal windows for multiple products, where only the last product is being displayed in each window. Attempted to assign id identifiers, but faced a problem where only the modal window of the first product functions correctly. wi ...

Understanding the concept of callbacks and scopes

While experimenting with the concept of callbacks, I encountered a scenario where I wanted to confirm that my understanding of the situation was correct. function greet(callback) { // 'greet' function utilizes a callback var greeting = "hi"; ...

Using Material UI with React hooks

I'm encountering an error while trying to incorporate code from Material UI. The error message is: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons: 1. Mismatc ...

Jest - Test snapshot failure occurred following the inclusion of "</React.Fragment>"

I encountered an error message while running Jest. As I am not very familiar with using Jest, I would appreciate any insights on why this test is failing. Results: Jest test result: - Snapshot + Received - <span - className="icon icon-dismiss size-2 ...

Exploring Angular: Looping through an Array of Objects

How can I extract and display values from a JSON object in a loop without using the keyValue pipe? Specifically, I am trying to access the "student2" data and display the name associated with it. Any suggestions on how to achieve this? Thank you for any h ...

How can Checkbox body styles be altered based on its input state in Mantine?

I am utilizing Mantine and need to create a custom styled container for a Checkbox input. This particular checkbox will alter its body styles based on the input state (checked or not checked). To achieve this, I must determine the pseudo class state of th ...

Error: The function $compile does not exist

Currently, I am working on developing an AngularJS directive using TypeScript. While testing my code in the browser, I encountered the following error: TypeError: $compile is not a function at compileComponent.js:14 Interestingly, the TypeScript compiler ...

Retain values of JavaScript variables acquired by their IDs even after a page refresh

I have a JavaScript function that retrieves HTML input values and inserts them into a table. However, when I refresh the page, those values are reset to null. How can I prevent this and keep the values visible after a refresh? I believe setting and getting ...

Using Javascript and Flask to ensure that at least one checkbox is selected from each category

I have a Flask template that uses a modal window to display a form. The form includes 3 drop-downs that work well with the required attribute, as well as two sets of checkboxes where the user must select one option from each set. I am new to JavaScript and ...