0

I have a string and want split them in an array based on type. I can extract numbers and floats like below, but is not complete to my goal

 var arr = "this is a string 5.86 x10‘9/l 1.90 7.00"
   .match(/\d+\.\d+|\d+\b|\d+(?=\w)/g)
   .map(function (v) {return v;});

 console.log(arr);

 arr = [5.86, 10, 9, 1.9, 7]

I would like have even chunk of string type and mixed like "x10‘9/l":

 arr = ["this is a string", 5.86, "x10‘9/l", 1.9, 7]

can someone figure out?

  • It is difficult to understand what you are asking. I think if you clarify the problem to yourself (and us, if needed), it will guide how you can go about solving this problem. Specifically: where do you split the input, and when do you cast pieces of the input to different types? – Jackson Apr 18 '18 at 19:56
  • Jack this is for PRO – Gael Sapori Apr 18 '18 at 20:19

2 Answers2

0
 const result = [];

 const str = "this is a string 5.86 x10‘9/l 1.90 7.00";

 result.push(str.split(" ").reduce((acc, part) => isNaN(part) ? acc + " " + part : ((acc && result.push(acc)), result.push(+part), ""), ""));
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
0

I came up with this:

 var arr = [];
 var str = "this is a string 5.86 x10‘9/l 1.90 7.00";
 arr.push(str.split(" ").reduce((acc, part) => isNaN(part) ? acc + " " + part : (arr.push(acc.trim(), +part), ""), ""));

 var result = arr,
     len = arr.length, i;

 for(i = 0; i < len; i++ ) {
     result[i] && result.push(result[i]);  // copy non-empty values to the end of the array
 }

 result.splice(0 , len);  // cut the array and leave only the non-empty values
 console.log(result);