Javascript/jQuery: remove all non-numeric values from array
Asked Answered
M

4

6

For an array: ["5","something","","83","text",""]

How to remove all non-numeric and empty values from an array? Desired output: ["5","83"]

Morganite answered 3/6, 2014 at 18:47 Comment(0)
M
7

Use array.filter() and a callback function that checks if a value is numeric:

var arr2 = arr.filter(function(el) {
    return el.length && el==+el;
//  more comprehensive: return !isNaN(parseFloat(el)) && isFinite(el);
});

array.filter has a polyfill for older browsers like IE8.

Martinemartineau answered 3/6, 2014 at 20:8 Comment(1)
your function throws error if the array that is being filtered contains 'null'. Sample input let arr = [ 0, 'a', () => console.log('?'), false, { a: '5' }, 7, 8, 9, '100', NaN, null, undefined, -Infinity, Infinity, ];Debrief
F
5

Here is a ES6 version which tests when values from an array match the regexp

let arr = ["83", "helloworld", "0", "", false, 2131, 3.3, "3.3", 0];
const onlyNumbers = arr.filter(value => /^-?\d+\.?\d*$/.test(value));
console.log(onlyNumbers);
Ferdelance answered 11/1, 2022 at 16:5 Comment(0)
H
1

I needed to do this, and following a bunny trail based on the answer above, I found out that this functionality has now been built in to jQuery itself in the form of $.isNumeric():

    $('#button').click(function(){
      // create an array out of the input, and optional second array.
      var testArray = $('input[name=numbers]').val().split(",");
      var rejectArray = [];

      // push non numeric numbers into a reject array (optional)
      testArray.forEach(function(val){
        if (!$.isNumeric(val)) rejectArray.push(val)
      });

      // Number() is a native function that takes strings and 
      // converts them into numeric values, or NaN if it fails.
      testArray = testArray.map(Number);

      /*focus on this line:*/
      testArray1 = testArray.filter(function(val){
        // following line will return false if it sees NaN.
        return $.isNumeric(val)
      });
    });

So, you essentially .filter(), and the function you give .filter() is $.isNumeric(), which gives a true/false value depending on whether that item is numeric or not. Good resources are available and easily found via google on how these are used. My code actually pushes the reject code out into another array to notify the user they gave bad input up above, so you have an example of both directions of functionality.

Henslowe answered 5/3, 2015 at 5:38 Comment(0)
R
-1

const arr = ["5","something","","83","text",""] const onlyNumbers = arr.filter((item) => typeof item === 'number')

this should work.

Reata answered 5/10 at 17:23 Comment(2)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Ennead
Please check "Desired output" in the asker's post. Then check the output of your code.Talavera

© 2022 - 2024 — McMap. All rights reserved.