I faced a problem with array convertions. I have an array with different values like:
let fruitsArry = ['apple', 'apple, mango, orange', 'orange'];
And I need to convert it to array like:
let fruitsArrSplited = ['apple', 'apple', 'mango', 'orange', 'orange'];
Could you suggest me any simple solution for this?
Thanks in advance.
6 Answers 6
Just use join(',') and split(','). And further use map() (optional) to remove the trailing and leading whitespaces. This will also ensures that there can be any amount of whitespaces between array element.
let fruitsArry = ['apple', 'apple, mango, orange', 'orange'];
var res = fruitsArry.join(',').split(',').map(item=>item.trim());
console.log(res);
Comments
Just join and split with the separator of the quoted part.
let fruitsArray = ['apple', 'apple, mango, orange', 'orange'],
result = fruitsArray.join(', ').split(', ');
console.log(result);
With white space after comma, you could split with optional whitepsace.
let fruitsArray = ['apple', 'apple, mango, orange', 'orange'],
result = fruitsArray.join().split(/,\s*/);
console.log(result);
2 Comments
Without join(" ,") which generates an unnecessary intermediate string, you may do as follows;
var fruitsArry = ['apple', 'apple, mango, orange', 'orange'],
result = fruitsArry.reduce((r,e) => r.concat(e.includes(",") ? e.split(/\s*,\s*/)
: e),[]);
console.log(result);
Comments
let array = ['apple', ' apple , mango , orange ', 'orange'];
newArray = array.join(',').split(/\s*,\s*/);
console.log(newArray);
I think this should do the trick. This will handle white space before and after each word too.
Comments
To answer your question simply you can use:
const af=a=>a.join(',').split(',').map(e=>e.trim()); // 45 character
and use it like:
let res = af(['apple', 'apple, mango, orange', 'orange']);
console.log(res);
Or if you prefer the long version:
/**
* Define the function
*/
function formatArray(arr) {
let tmp: string[];
let result: string[] = [];
tmp = arr.join(',').split(',');
tmp.forEach((el, i) => {
let str = el.trim(); // this is to remove the extra spaces
result.push(str); // add the element to final array
});
return result;
}
And use it as:
// The orignal array
let arr = ['apple', 'apple, mango, orange', 'orange'];
arr = formatArray(arr);
console.log(arr);
Note that trimming part in the function, is an option you might not need this in your case but I figured out this is what you might want.
Comments
You may use _js. Underscore Js Documentation
let fruitsArry = ['apple', 'apple, mango, orange', 'orange'];
var res = _.chain(fruitsArry).map(function(fruit) { return fruit.split(',') }).flatten().value()
console.log(res)
reactjsflag