Using JS .map() to get only numbers from an array of values

← PrevNext →

Let us assume, I have alpha-numeric values in an array. For example, let arr = ['ab51', 'ab67']. I want to extract only the numbers from the values, that is 51, 67 etc. The function that I can use in this case is the .map() function, which will allow me to quickly and efficiently extract numbers from the values.

Let's see an example first then I'll explain how the map() function works.

  <p id="result"></p>
  const arr = ['ab51', 'ad67', 'b-9', 'b81', 'cp11'];

  const get_numbers_from_text = (val) => {
     return val.replace(/\D+/g, '');

  let a_new_array =;

  let result = document.getElementById('result');
  result.innerHTML = a_new_array;
Try it

The map() function iterates or loops through an array using a callback function (or the mapping function). The call back function "get_numbers_from_text()" takes an argument, the array value. The function then returns only number after replacing the text (or string) value.

There's another method in JavaScript that you can use to perform a similar task, that is, filtering out only numbers from an array. See this example.

Related... How to get numbers from a String in JavaScript? Using two very simple methods.

Happy coding. 🙂

← PreviousNext →