4

I have a snippet of code where I am trying to parse a longer string with special characters into an array with no spaces or special characters.
input: name: this is some stuff, name2: this is more stuff
desired output: [name,this is some stuff,name2,this is more stuff]
current output: z.trim isn't a function

function parseOrder(custOrder) {
  const custOrderArr = custOrder.split(','); 
  const trimedArr = custOrderArr.map((x) => x.trim());
  const numberArr = trimedArr.map((y) => y.split(':'));
  const processArr = numberArr.map((z) => z.trim());
  console.log(processArr);
}

Why does trim work the first time and not the second?

3
  • in some of the iterations your var z may not be of type string, post your dataset you're working with. Commented Jan 6, 2020 at 16:23
  • You're creating an array of arrays (stored in numberArr). Maybe you'd want to take a look at array.flatten or use regex. Commented Jan 6, 2020 at 16:25
  • numberArr looks like it is going to be an array of arrays of strings Commented Jan 6, 2020 at 16:25

2 Answers 2

2

You can not trim an array. But you could map the array and trim the values.

This result features Array#flatMap for preventing arrays with pairs.

function parseOrder(custOrder) {
    return custOrder
        .split(',')
        .flatMap(y => y.split(':').map(x => x.trim()));
}


var input = 'name: this is some stuff, name2: this is more stuff ';

console.log(parseOrder(input));

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

1 Comment

yup, totally skipped over the fact it was an array of arrays, not just an array.
1

Try to split by two signs, then trim your elements:

const result = str.split(/[\:,]+/).map(s => s.trim());

An example:

let str = 'test: It is me, test2: it is me 2 ';
console.log(str.split(/[\:,]+/).map(s => s.trim()));

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.