Bharadwaj
Bharadwaj

Reputation: 11

Separate Fraction accordingly using javascript

I can I separate fractions accordingly as numerator and denominator using javascript split.

var str="1/2+2/4";    
str.split('/').split('+');//not Working

Now I want it like num=[1,2] and den=[2,4]

Upvotes: 0

Views: 355

Answers (1)

Ele
Ele

Reputation: 33726

You're trying to split an array.

An alternative is splitting the string by symbol + and then execute the function reduce.

var str="1/2+2/4+3/4";
var result = str.split('+').reduce((a, c) => {
  var [num, den] = c.split("/");
  a.den.push(den);
  a.num.push(num);
  
  return a;
}, {num: [], den: []});

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Upvotes: 1

Related Questions