Skip to content
Advertisement

Extract Numbers from Array mixed with strings – Javascript

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.

Advertisement

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);
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement