Cross browser array filtering in javascript

I'm facing a challenge that I haven't been able to find a solution to yet. I have an array, let's say var oldArr=['one','two','3'];, and I need to create a new array containing only the string values. Currently, I'm using the Array.filter method which works fine. However, someone mentioned that it may not be supported in all browsers. So, I'm wondering how I can filter my array with a solution that works across all browsers.

Here's my current code:

var oldArr=['one','two','3'];
newArr=oldArr.filter(function(a){
return !a.match(/\d/);
});
alert(newArr);

Thank you for your help in advance.

Answer №1

Perhaps this is what you are looking for

if (!Array.prototype.filter) {
    Array.prototype.filter = function(fun /*, thisp*/) {
        var len = this.length >>> 0;
        if (typeof fun != "function") {
            throw new TypeError();
        }

        var res = [];
        var thisp = arguments[1]; 
        for (var i = 0; i < len; i++) {
            if (i in this) {
                var val = this[i];
                if (fun.call(thisp, val, i, this)) {
                    res.push(val);
                }
            }
        }

        return res;
    };
}

var oldArr = ['one','two','3'];
    newArr=oldArr.filter(function(a){
    return !a.match(/\d/);
});
console.log(newArr);

Reference: MDN.

DEMO.

Answer №2

let originalArray = ['one', 'two', '3'];
let newArray = [];
for (let index = 0; index < originalArray.length; index++) {
    if (isNaN(originalArray[index])) {
        newArray.push(originalArray[index]);
    }
}

isNaN is a function that determines if a value can be converted to a number and is compatible across different web browsers.

If you are looking to extract items that are actually numbers from the array, you can simply negate the isNaN function in the conditional statement:

if (!isNaN(originalArray[index])) {

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

Leveraging AJAX with React Router

Currently tackling a project utilizing React Router, encountering some challenges with data flow. Each page triggers an AJAX call to fetch data for the component. These calls have been placed within componentDidMount: // The following code is in ES6 comp ...

Refreshing Child's Activities

In my scenario, I am displaying data in a child action and utilizing buttons to modify the displayed information. Here is an example of how I am achieving this: Index.cshtml <head> <script type="text/javascript"> $("#RefreshView").on ...

Ways to extract text from a temporary element

Here is my HTML code: <div class="p-login-info" ng-show="loggedOut()">My text.</div> This is the corresponding JavaScript code: var e = element(by.className('p-login-info')); e.getText() .then(function(text){ var logoutText = ...

Disable the swipe feature on a Bootstrap carousel to prevent users from navigating through slides on mobile devices. The attribute data-touch="

I've been attempting to deactivate the swipe function on my Bootstrap 4 carousel in my project, but it's proven to be quite challenging. Despite it being a basic carousel, I'm finding it difficult to turn off this feature. What am I missing ...

Securely package tailor-made services within an application

Recently, I have been researching how to create custom services for AngularJS. However, all the examples I found demonstrate defining the service directly on my app using myApp.factory(...). For reference, you can check out the official docs for an example ...

Listen for a click event on an Unordered List using addEventListener

Struggling to transform a for loop that iterates through an unordered list of hyperlinks and adds an 'onclick' function to each into one using an event listener instead. Unfortunately, I have not been able to create a functional solution. Below ...

Discover the DOM events present in an HTML response

When sending multiple HTTP requests to a server and receiving a HTML + JS response, I need to determine which responses trigger JS alerts or DOM-based events. Node.js is being used to send the requests. Especially in cases where there is local JS on the c ...

Utilizing .isDisplayed() in conjunction with .each() in ProtractorJS for Angular: A guide

Currently, I am working on setting up a test within my Angular application. The goal of this test is to click on an element and check if a specific object is displayed. While I believe the code provided below should work, I am aware that the isDisplayed( ...

Managing Page Refresh using AngularJS Service and Views

In my single-page application (SPA), I have implemented two views: a list view and a detail view. To pass data between these two controllers, I am utilizing a service called StateService. The issue arises when the user refreshes the browser page, causing ...

In React using Flow Type, the syntax [...mySet] doesn't function as expected, while Array.from(mySet) successfully converts the

Why is it that with React and Flow Type, the line of code displaying [{}] when using JSON.stringify([...mySet]) but shows the correct values with JSON.stringify(Array.from(mySet))? The issue seems perplexing as this behavior cannot b ...

Create a variety of exam papers using text documents

Looking to create a simple Java program, but unsure of where to start. How can I go about developing a flow or pseudocode before diving into the actual programming process? I have two text files filled with questions - one holds 60 questions and the other ...

What are the key steps in pinpointing and saving the central positions of dots within a grid?

I am currently seeking advice on the next steps and how to proceed with my project. Here is some context: The task at hand involves finding the center of circles within a grid placed on an image that was originally 1260x683 pixels. The grid consists of 27 ...

Is it possible to have a page transition when clicking a form button

I've been experimenting with this on my website Everything is functioning well, except when I add data-ftrans="slide" to a form button. For example: <form action"http://google.com"> <button data-ftrans="slide" type="submit" style="h ...

Discovering the magic of nesting maps in React-Native without the need for

I am currently developing a react-native app that retrieves its data through an API. I am working on implementing a new feature where the information is grouped by date. The JSON data structure sent by the API looks like this: { "channel_count" ...

Transferring identification data between views within an application (AngularJS, NodeJs, HTML)

I'm working on an HTML page that lists users from MongoDB. The page allows for deleting and updating users. I am encountering an issue with the update button - I want a new HTML page to appear with a form when the button is clicked, capturing the user ...

5 Simple Steps for Adding a Value to a Popup Textbox Automatically

I want to send a value to another php page and then display the values. How can I achieve this? Here is the PHP code snippet: if(!empty($_POST["mytext"])) { for ($x=1; $x<=$a; $x++) { echo $txtLine[$x] = $_POST['mytext'.$x]; } } B ...

retrieving the parent of the a tag from a jquery form

When using the jQuery code below: $('#trade-offer form').on("submit", function(event) { event.preventDefault(); var stock = $(this).closest('.allloopedover'); console.log(stock); return; $.ajax({ url: ajaxur ...

If the console is not open, console.log will not update

When I press the reset button on my simple function, I expect to see the FIRST console.log in the console right away, displaying an array with 5 objects. After 5 seconds, the SECOND console.log should be displayed with an empty array. Everything seems to w ...

Steps for including a new script in package.json

Is there a way to add the script dev to my package.json from the terminal? I attempted to manually add it using a text editor, but when I try to run: npm run dev I encounter some errors. Is there a way to include this script through the command line? E ...

What is the best way to assign a distinct index value to each object in an array

When I use the function below to add an index to each array object, all IDs end up with the same value when I check console.log: var foo = [...this.props.articleList]; foo.forEach(function(row, index) { row.id = index+1; }); console.log(foo); My des ...