1

Say I have the following array:

const arr = [ 'a,b,c', 'd,e,f', 'g,h,i' ];

I want to get to

[ 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i' ]

I am currently using reduce https://jsbin.com/xejedexada/edit?js,console

arr.reduce((a,c) => (typeof a == 'object' ? a : a.split(',')).concat(c.split(',')));

But I wonder if there is a better way to do this.

Austin France
  • 2,381
  • 4
  • 25
  • 37

4 Answers4

1

You can use .join() and .split() methods:

const arr = [ 'a,b,c', 'd,e,f', 'g,h,i' ];

const result = arr.join().split(",");

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

References:

Mohammad Usman
  • 37,952
  • 20
  • 92
  • 95
1

Use reduce method and split to split the string by comma

let m = ['a,b,c', 'd,e,f', 'g,h,i'];

let x = m.reduce(function(acc, curr) {
  acc.push(...curr.split(','))
  return acc;
}, [])
console.log(x)
brk
  • 48,835
  • 10
  • 56
  • 78
0

You do not need reduce for that just use join(',') and split(','):

const arr = [ 'a,b,c', 'd,e,f', 'g,h,i' ];
var res = arr.join(',').split(',');
console.log(res);
Ankit Agarwal
  • 30,378
  • 5
  • 37
  • 62
0

simply concat the splited subarray

const arr = [ 'a,b,c', 'd,e,f', 'g,h,i' ];
console.log( [].concat(...arr.map(a=>a.split(','))) )
apple apple
  • 10,292
  • 2
  • 16
  • 36