Home > OS >  Parsing JavaScript string into 2 arrays
Parsing JavaScript string into 2 arrays

Time:12-12

You have a string that is in a following format: "Applejack=A.J. Applecar,Lemon Vodka=AlfieCocktail Sunset SexOnTheBeach" and etc.

In Javascript (use .split()), write code to parse a string like this(can be 100000 characters long) that puts the input in 2 different arrays(array key, array values) such that the arrays would llok like the following:

key = ["Applejack", "Lemon Vodka"]

values = ["A.J Applecar","AlfieCocktail Sunset SexOnTheBeach"]

CodePudding user response:

key = string.split(',').map(x=>x.split("=")[0])
values = string.split(',').map(x=>x.split("=")[1])

CodePudding user response:

You could do something like this

var str = "Applejack=A.J. Applecar,Lemon Vodka=AlfieCocktail  Sunset   SexOnTheBeach";
var first = str.split(',');
var keys = [];
var values = [];
for(let i = 0; i < first.length; i  ){
  let in_two = first[i].split('=');
  keys.push(in_two[0]);
  values.push(in_two[1]);
}
console.log(keys);
console.log(values);

CodePudding user response:

You can do it like this:

let str = "Applejack=A.J. Applecar,Lemon Vodka=AlfieCocktail  Sunset   SexOnTheBeach";
let allValues = str.split(','), keys = [], values = [];
allValues.forEach(value => {
    const [k,v] = value.split('=');
    keys.push(k);
    values.push(v);
})

console.log(keys,values);

  • Related