Extract Numbers from Array mixed with strings – Javascript Code Answer

Hello Developer, Hope you guys are doing great. Today at Tutorial Guruji Official website, we are sharing the answer of Extract Numbers from Array mixed with strings – Javascript without wasting too much if your time.

The question is published on by Tutorial Guruji team.

I have an array from strings and numbers. I need to sort the numbers or better to extract only the numbers in another array. Here is the example:

 const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.']

I need to make it like this

 const filtered = [23456, 34, 23455]

I used split(‘ ‘) method to separate them with comma but don’t know how to filter them for JS they all are strings.

Answer

This could be a possible solution,

See MDN for map(), replace(), trim() and split()

const myArr = ['Prihodi 23456 danaci 34 razhodi 23455 I drugi.'];
filtered = myArr[0].replace(/D+/g, ' ').trim().split(' ').map(e => parseInt(e));
console.log(filtered);

OR

const regex = /d+/gm;
const str = `Prihodi 23456 danaci 34 razhodi 23455 I drugi`;
let m;
const filter = [];
while ((m = regex.exec(str)) !== null) {
  // This is necessary to avoid infinite loops with zero-width matches
  if (m.index === regex.lastIndex) {
    regex.lastIndex++;
  }

  // The result can be accessed through the `m`-variable.
  m.forEach((match, groupIndex) => {
    filter.push(parseInt(match))
  });
}

console.log(filter);
We are here to answer your question about Extract Numbers from Array mixed with strings – Javascript - If you find the proper solution, please don't forgot to share this with your team members.

Related Posts

Tutorial Guruji