0

I have a Javascript object like

Object = { "ratio1" : "12+45*36",
                 "ratio2" : "34+45*16",
                  "ratio3" : "17+25"}

I am trying to split the values like the values before + in one array and values after + in one array . so the output should be like

Array1= ["12" , "34" , "17"]
Array2 = ["45" , "36" , "45","16","25"].

To perform this I am iterating through the keys and getting the values first then I am again iterating through the values array I am splitting it using

ratioArray.split("+");

This gave me [[" 12" , "45*36"], [" 34", "45*16"], [" 17", "25"]]

Now again I have iterate through all the three arrays and split using second delimiter. Is there any efficient way to perform this so that I can reduce these many iterations

3
  • It's the right way.. Commented Sep 22, 2017 at 0:37
  • Actually I am stuck here . I am unable to perform the split with the resultant array :( Commented Sep 22, 2017 at 0:40
  • str.split(/[+*]/) Commented Sep 22, 2017 at 0:44

3 Answers 3

1

const ratios = {
  "ratio1" : "12+45*36",
  "ratio2" : "34+45*16",
  "ratio3" : "17+25"
}


const nums = Object.keys(ratios)
  .map(key => ratios[key]
    .replace(/[+*]/g, '|')
    .split('|')
  )

const [ array1, array2, array3 ] = nums

document.querySelector('pre').innerText = 
  `array1 === [${array1}]\n` +
  `array2 === [${array2}]\n` +
  `array2 === [${array3}]\n`
<pre />

Sign up to request clarification or add additional context in comments.

Comments

0

var Object = {
    "ratio1": "12+45*36",
    "ratio2": "34+45*16",
    "ratio3": "17+25"
}

var Array1 = [],
    Array2 = [],
    temp;
for (var key in Object) {
    temp = Object[key].split('+');
    Array1.push(temp[0])
    temp = temp[1].split('*')
    for(var i = 0; i < temp.length; i++){
      Array2.push(temp[i])
    }
}

console.log('Array1:['+Array1[0]+','+Array1[1]+','+Array1[2]+']')
console.log('Array2:['+Array2[0]+','+Array2[1]+','+Array2[2]+','+Array2[3]+','+Array2[4]+']')

2 Comments

This is working like a charm . thank you so much . can you help me to make the final merging to single array as dynamic .
@Karthi what do you mean? explain
0

You can do something like this.

object = {
  "ratio1": "12+45*36",
  "ratio2": "34+45*16",
  "ratio3": "17+25"
}

var array1 = [],
  array2 = [];

for (var key in object) {

  var _o = object[key].split("+");
  array1.push(_o[0]);

  _o[1].split("*").forEach(function(num) {
    array2.push(num);
  })

};

console.log("array 1", array1);
console.log("array 2", array2)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.