Trim the final digits from the arrays

I have an array that contains various strings:

var arr = ['1234','23C','456','356778', '56']

My goal is to filter out array elements that are less than 3 characters or more than 4 characters. The resulting array should only include elements with 3 or 4 characters, like so:

arr = ['1234', '23C', '456'];  //only 3 and 4 character strings in the array

Additionally, I would like to modify the array further by removing the last digit from any element that has more than 3 characters. The final array should look like this:

arr = ['123', '23C', '456'];

Answer №1

To start with, you can simply utilize the filter function to eliminate numbers that do not consist of 3 digits.

var values = [1234, 234, 456, 356778, 56];
var filteredValues = values.filter(function(number) {
  return number < 1000 && number >= 100;
});

console.log(filteredValues);

Next, for the second part, the map method can be used. Simply convert the number to a string, check if its length is more than 3, take the substring containing the initial three characters of the string, and then convert it back to a number.

var nums = [1234, 123, 4567, 3333];
var updatedNums = nums.map(function(value) {
  value = value.toString().substring(0, 3);
  return parseInt(value);
});

console.log(updatedNums);

Answer №2

If all you need are Array.filter and Array.map, as well as converting strings to numbers.

let arr = [1234, 234, 456, 356778, 56];

let newArr = arr.filter((num) => {
  let str = '' + num;
  return str.length === 3 || str.length === 4;
});

Now for the second scenario:

let newArr = arr.map((num) => {
  let str = '' + num;
  
  if (str.length > 3) {
    str = str.substring(0, 3);
  }
  
  return +str;
});

Answer №3

function filterArrayByLength(arr,lowLimit,highLimit){
    var filteredArr=[];
    for(i=0;i<arr.length;i++){
         value=arr[i];
         length=value.length;
         if(length>=lowLimit&&length<=highLimit){
          if(length>lowLimit){
          value=value.substring(0,lowLimit);
          }
          filteredArr.push(value);
         }
     }
     return filteredArr;
}

var array = ['1234','234','456','356778','56'];
array=filterArrayByLength(array,3,4);
console.log(array);

Answer №4

If you want to determine whether a number is either 3 or 4 digits long, simply check if the number falls within the range of 100 and 9999

  let filteredNumbers = arr.filter(function(num) {
    // Check if it's a 3 or 4 digit number
    return num >= 100 && num < 10000;
  });

To truncate four-digit numbers to three digits, you can divide each four-digit number by 10 and then round down to the nearest integer

  let truncatedResults = filteredNumbers.map(function(number) {
    return number >= 1000 ? Math.floor(number / 10) : number;
  });

Answer №5

This method involves converting the given array into a specific string format 1234,23C,456,356778,56, and then using regular expressions to extract the desired elements.

var arr = ['1234','23C','456','356778', '56'];

console.log(String(arr).match(/\b\w{3}(?=\w?\b)/g));

Simplified Explanation:

Identify all substrings that begin with a word boundary (\b, following a comma or at the start of the string), consist of three alphanumeric characters, and potentially have one extra character before the next word boundary (comma or end of string).

It's important to note that this approach can handle string values, as long as they are made up of alphanumeric characters to maintain the integrity of the word break logic (\b).

Answer №6

 const validNumbers = updated_ImportDetails.ImportData.filter((num) => num.length > 2 && num.length < 4);

const uniqueNumbers = validNumbers.map((num) => num.substring(0, 3)).filter((elem, index, self) => index === self.indexOf(elem));

I found this solution to be effective.

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

Oops! Make sure to explicitly allow the dependency @types/html2canvas by adding it to the "allowedNonPeerDependencies" option

After installing the html2canvas package in my Angular library project, I encountered an error when compiling in production mode using the command ng build --prod. The specific error message is as follows: ERROR: Dependency @types/html2canvas must be exp ...

Reactivating a React hook following the execution of a function or within a function in ReactJS

A new react hooks function has been created to retrieve data from an API and display it on the page: function useJobs () { const [jobs, setJobs] = React.useState([]) const [locations, setLocations] = React.useState({}) const [departments, setDepartm ...

Featherlight is experiencing issues with running Ajax requests

I'm currently working on integrating an ajax photo uploading script into a Featherlight lightbox, but I'm running into issues! If anyone could help me figure out what's going wrong, that would be greatly appreciated. I've already includ ...

Guide to integrating react-phone-number-input into material-ui TextField

Would it be possible for me to use a Material UI TextField component as the inputComponent prop for the PhoneInput component from react-phone-number-input? I am facing an issue where I am unable to apply the ref successfully. Even though I can see the Mat ...

Executing Javascript dynamically in VueJS: Learn how to run code from a string efficiently

Currently, I am developing a website with VueJS that enables selected users to upload scripts for automatic execution upon page load. For instance, here is an example of the type of script a user may input: <script src="https://cdnjs.cloudflare.com/aja ...

Executing php class method through ajax with jQuery without requiring a php handler file

How can I trigger a PHP class method using AJAX with jQuery without the need for a separate PHP handler file? Here is my PHP Class animal.php:- <?php class animal { function getName() { return "lion"; } } ?> jQuery code snippet:- ...

Utilizing the getJSON Method to Automatically Fill a Dropdown Selection Element

I am looking to populate a dropdown select menu with bank names and IIN numbers obtained from the following JSON: JSON Data : {"status":true,"message":"Request Completed","data":[{"id":1,"activeFlag":1,"bankName":"Union Bank of India","details":"Union Ba ...

determine the vertical dimension of the horizontal scrollbar

I ran into an issue where I needed to determine the height of a horizontal scrollbar. This question and answer recommended using the clientHeight property to calculate the difference. Unfortunately, this method no longer works as shown here: https://jsfid ...

A PHP "for" loop that iterates through an array and prints out all even numbers, along with calculating the sum of all odd numbers

I have been given the task to create a loop that showcases all even numbers in one column, while also calculating and displaying the sum of all odd numbers in an array. Here's what I have done so far: <?php $numbers = array(1, 2, 3, 4, 5, 6, 7, 8, ...

Adding data to a subdocument array with Mongoose's $push method

Here is the model that I am working with: var Customer = mongoose.model('Customer', { firstname : String, lastname : String, phone : String, street : String, city : String, state : String, zip : String, fixed : Bo ...

Leveraging dynamic anchor tags within a Chrome extension

In my current project, I am dynamically generating anchor tags and using them to redirect to another page based on their unique IDs. While I have successfully implemented this feature using inline scripts in the past, I ran into an issue with Chrome exte ...

Tips on using Ajax to post in HTML

Here is the code I have been working on: <script type="text/javascript"> var xmlDoc; var xmlhttp; function loadRates() { xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = readRates; xmlhttp.open("GE ...

Employing a for loop to verify the existence of a JSON key

Currently, I am attempting to loop through an EJS JSON object and verify the existence of values. If a value does exist, I want to add the corresponding URL to an array further down. Upon loading the page, I am encountering an issue where I am informed th ...

What steps can be taken to ensure that a dropdown menu responds instantly to the JavaScript code provided?

Upon discovering this code snippet in a different answer (on jsfiddle), I noticed that it allows for the appearance of a text box when the user selects 'other' from the dropdown menu. However, when I include '<option value='0' s ...

A guide on setting up dual observables in Angular 2

Currently, I am implementing Observable in angular 2 with rxjs. As part of my demonstration, I have utilized fromEvent in a Plunker. Here is the link to my demo: https://plnkr.co/edit/zkgEcdn21CvIKoOycUOy?p=preview In this demo, I have included two input ...

The dynamic change of a required field property does not occur

I am facing an issue where one of my fields in the form should be mandatory or not based on a boolean variable. Even if the variable changes, the field always remains required. I'm puzzled about why my expressionProperties templateOptions.required is ...

Issues with jQuery slide operation

I'm facing an issue with jQuery and I can't figure out where it's coming from. Here is the error message that keeps showing up in the console: Uncaught TypeError: Object [object Object] has no method 'getElement' script_16.js:46Un ...

Exploring the Benefits of Using Gatsby with Material-UI: The Importance of Creating a Page

Upon reviewing the gatsby demo showcased on the material-ui project github page, I found myself puzzled by a few lines of code. In the specific file getPageContext.js export default function getPageContext() { // Ensuring each server-side request has i ...

Why is the Twitch api map function returning nothing, while the console log is showing output?

Presently, my Nextjs page is making multiple Twitch API calls successfully and displaying the correct data. However, one of the mapping functions is failing to render anything on the page, even though the console log shows the data. Although I am relativel ...

Sorting a select element using Javascript/JQuery while taking into consideration the label attribute present in the options

It came to my attention that the jQuery options and examples only covered the text and value attributes, causing errors when attempting to add the label attribute. I am looking for a way to include the label attribute in the sorting process, especially whe ...