Array of strings containing numbers

easy

By - Aman Pareek

Last Updated - 26/08/2024

Problem Statement

Create a JavaScript function that returns a new array containing only the strings from the original array that include numeric characters.

const input = ["hey", "age = 12", "pi = 3.14"];

Example 1

Input: array = ["hey", "age = 12", "pi = 3.14"]

Output: ["age = 12", "pi = 3.14"]

Solution 1: Using filter Method

function method1(arr) {
  return arr.filter((v) => /[0-9]/g.test(v));
} 

const array1 =  ["hey", "age = 12", "pi = 3.14"];
method1(array1);  //output: ["age = 12", "pi = 3.14"] 

Solution 2: Using forEach Method

function method2(arr) {
  const result = [];
  arr.forEach((str) => {
    if (/[0-9]/g.test(str)) {
      result.push(str);
    }
  });
  return result;
} 

const array1 =  ["hey", "age = 12", "pi = 3.14"];
method2(array1);  //output: ["age = 12", "pi = 3.14"] 

Solution 3: Using forEach with map for Transformation

function extractNumericStrings(arr) {
  const result = [];
  arr.map(str => {
    if (/\d/.test(str)) {
      result.push(str);
    }
  });
  return result;
} 

const array1 =  ["hey", "age = 12", "pi = 3.14"];
extractNumericStrings(array1);  //output: ["age = 12", "pi = 3.14"] 

More Problems Solutions

Is array equal