Is there a way to choose particular characters in an array in Javascript without relying on RegEx?

As I tackle multiple coding challenges in preparation to join a coding bootcamp, I find myself stuck on the same problem for days.

Despite scouring the internet and experimenting with different solutions, I am unable to pass their specific test on the console.

Challenge:

Your task is to create a function called extractPassword that takes an array of characters (including some trash characters) and returns a string containing only valid characters (a - z, A - Z, 0 - 9).

Here are some examples:

extractPassword(['a', '-', '~', '1', 'a', '/']); // should return 'a1a'
extractPassword(['~', 'A', '7', '/', 'C']); // should return 'A7C'

Attempt 1:

Initially, I attempted using RegEx:

var newArray = [];

var extractPassword = function(arr){
 
    console.log('arr: ' + arr);
    
    return arr.join('').match(/[a-zA-Z0-9]/g);
};

console.log(extractPassword(['a','-','~','1','a','/']).toString().replace(/,/g, ''));

The output 'a1a' was what I desired, but unfortunately, it triggered an error: >>>Code is incorrect. We prefer a different approach instead of RegExs.

Attempt 2:

Subsequently, I opted for a function combined with a for loop and an if statement:

var newArray = [];

extractPassword(['a','-', '~', '1', 'a', '/']);

function extractPassword(arr){
    
    console.log('arr: ' + arr);

    var arrayToString = arr.join('');

    console.log('arrayToString: ' + arrayToString);
    

    
    for (var i = 0; i < arrayToString.length; i++){
        var charCode = arrayToString.charCodeAt(i);

        
        console.log('charCode ' + i + ':' + charCode);

        
        if((charCode > 47 && charCode < 58) || (charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123)){
            newArray.push(arr[i]);
            console.log('newArray: ' + newArray);
        }
        
    }

    console.log('Final string: ' + newArray.join(''));
}

Although this approach also yielded 'a1a', the console still returned an error: >>Code is incorrect. Your function is not returning the correct value.

If anyone has an alternative solution to achieve the desired outcome, please share. Despite numerous attempts, I remain stuck and unable to progress.

Answer №1

For eliminating characters in an array that fall outside the ranges of 0-9, A-Z, and a-z, consider using the .filter() method, followed by .join() to combine the filtered characters into a single string. Here's how you can achieve this:

const getFilteredPassword = arr => arr.filter(ch => (ch >= '0' && ch <= '9') || (ch >= 'A' && ch <= 'Z') || (ch >= 'a' && ch <= 'z')).join('');

console.log(getFilteredPassword(['a', '-', '~', '1', 'a', '/'])); // output: 'a1a'
console.log(getFilteredPassword(['~', 'A', '7', '/', 'C'])); // output: 'A7C'

Remember, direct character comparison is possible without invoking .charCodeAt() to compare against ASCII values.

Answer №2

If you want to achieve this task without using Regex, one approach is to utilize the Array.filter() method along with String.codePointAt(). By applying this filter to your input data, which is conveniently in array format already, you can extract the desired alphanumeric characters.

const firstCode = 48; // A
const lastCode = 122; // Z

const isAlphanumeric = (char) => {
  const code = char.codePointAt(0);
  return (code >= firstCode) && (code <= lastCode);
};

const getPassword = (inputArr) => {
  const filteredChars = inputArr.filter(isAlphanumeric).join("");
  return filteredChars;
};

console.log( getPassword(['a', '-', '~', '1', 'a', '/']) ); // 'a1a'
console.log( getPassword(['~', 'A', '7', '/', 'C']) ); // 'A7C'

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

Having trouble updating attribute through ajax requests

How can I set attribute values using ajax-jquery? Here are some snippets of code: HTML_CODE ========================================================================== <div class="col"> <ul class="nav nav-pills justify-content-end& ...

Insert the object into a designated location within a multi-dimensional array

I've integrated a tree view into my Angular project and I'm looking to add an object to a specific position within an array. array const TREE_DATA: TreeNode[] = [{"name":"Demo","id":"demo_1","children ...

Using jQuery to iterate over array elements and apply a new class

I currently have the following elements with the 'play' class added to them: $('#a1').addClass('play'); $('#a3').addClass('play'); $('#a5').addClass('play'); $('# ...

Having trouble sending an array's JSON data to a web service using Angular

I am working with a table where each cell in the rows contains form fields. The table also has two buttons: one button adds a new row to the table, and the other sends all the rows. Below is the code snippet for adding new blank rows: $scope.attributes = ...

What is the best method for incorporating a Vue 2 component into an HTML single file that relies on Vue 3's UMD build?

Exploring the utilization of (an intricate multi-select component with nested options) in a standalone Vue 3 single local HTML file, without relying on the Vue CLI for this specific task. When using the UMD build for Vue 2, it functions as outlined below ...

Leveraging the search feature within Google scripts to manipulate arrays

I'm facing a challenge in developing a function to search for regex in a cell and return a specific value if the result is found. The function works fine on an individual cell, but I can't seem to get it to work when applying it as an array to ce ...

Adjust the Size of iFrame Content Using JavaScript

Is there a way to automatically resize the content within an iFrame so it fits without adjusting the size of the iFrame itself? I want all the content inside the iFrame to scale down if there is too much to display. Does anyone have any suggestions on how ...

The Vue data property fails to update when enclosed within the <code> tag

Here is my component: <template> <div> <select v-model="minecraftVersion"> <option v-for="version in minecraftVersions" :key="version.version" :value="version.version" >{{version.version}}& ...

What advantages and disadvantages come with using timeouts versus using countdowns in conjunction with an asynchronous content loading call in JavaScript/jQuery?

It seems to me that I may be overcomplicating things with the recursive approach. Wait for 2 seconds before loading the first set of modules: function loadFirstSet() { $('[data-content]:not(.loaded)').each( function() { $(this).load($(thi ...

What sets the screen property apart from the window property?

I'm working on a Web application and I need to access the browser window's Height & Width. Initially, I used JavaScript properties Screen.Width , Screen.Height to get these values. Later on, I came across another property called Window.Width , Wi ...

Is there a way to incorporate a base64 encoded image from a text file into an HTML image?

I have several images stored as base64 blobs in a remote location. Let's focus on one specific image: llorkcir.txt data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wCEAAkGBxISEhASEBAQDxAQDw8QEA8PEA8PDw0PFRIWFhURFRUYHSggGBolGxUVITEhJSkrLi4uFx8zODMt ...

Deciphering JSON to Use with jQuery Calendar

Currently, I am faced with the task of utilizing the PHP json_encode function to convert JSON data for a calendar rendering jQuery plugin called FullCalendar. After extracting event information from a MySQL database and encoding it into a JSON string, I e ...

Creating head tags that are less bouncy

After running my code, I noticed that the headlines didn't transition smoothly - they seemed to jump rather than flow seamlessly. To address this issue, I attempted to incorporate fadeIn and fadeOut functions which did improve the smoothness slightly. ...

Creating an X pattern on an HTML5 canvas and detecting intersections with a perimeter

I am currently developing a maze game using HTML 5. Below is the function I have implemented to draw an "X" on the canvas (the player will guide the X through the maze using touchpad). dim = 8; function rect(x,y,xdim){ ctx.beginPath(); ctx.moveT ...

changing unique characters in JavaScript document

I am currently utilizing DocXTemplater to export a table to a Word document. Within the JavaScript file, there is a module containing special characters that CRM does not permit when creating a file. I attempted to remove the variables with special charac ...

What is the appropriate method for transferring a JSON string from JavaScript to PHP and vice versa?

As I strive to transmit a small amount of data from JavaScript by means of XMLHttpRequest and a Json string to a PHP script for processing, only to receive a corresponding Json string in response, I have encountered numerous obstacles and various technique ...

Explain the function of the npm run build command and describe the role of webpack in generating a bundle file

Exploring the Contrasts: npm run build vs. npm install webpack Let's delve into the distinctions between these two commands ...

Tips for toggling CSS classes based on the user's current page

<nav id="navMenu" class="navMenu"> <ul> <li class="active homePage"> <a href="index.php" title="Homepage">Home</a> </li> <li class="resourcesPage"> <a href="re ...

Comparison of list mutation using for-in loop vs. range(len) in Python

What is the reason for the lack of mutation in the list passed below: def modify(listarg): for x in listarg: x=x*2 While this results in mutation: def modify(listarg): for x in range(len(listarg)): listarg[x]=listarg[x]*2 ...

What is the process for integrating third-party packages into an Angular 2 CLI project?

I've been diving into an Angular 2 project lately that follows the Angular 2 CLI structure. Adding libraries like moment, ng-material2, and ng2-bootstrap has been a smooth process for me. However, things get tricky when I try to integrate a package su ...