Erik Edgren Erik Edgren - 3 months ago 7
Javascript Question

Split an array cause an error: not a function

I want to split an array that already have been split.

var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(',');
var array_s = array_dt.split('|');
console.log(array_s);


That code returns
TypeError: array_dt.split is not a function
.

I'm guessing that
split()
can not split an array. Have I wrong?

Here's how I want it to look like. For
array_dt
:
2016-08-08,2016-08-07,2016-08-06,2016-08-05,2016-08-04
. For
array_s
:
63,67,64,53,63
. I will use both variables to a chart (line) so I can print out the dates for the numbers. My code is just as example!

How can I accomplish this?

Demo

Answer

If you want to split on both characters, just use a regular expression

var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);

console.log(array_dt)

This will give you an array with alternating values, if you wanted to split it up you can do

var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);

var array1 = array_dt.filter( (x,i) => (i%2===0));
var array2 = array_dt.filter( (x,i) => (i%2!==0));

console.log(array1, array2)

Or if you want to do everything in one go, you could reduce the values to an object

var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';

var array = string.split(/[,|]/).reduce(function(a,b,i) {
  return a[i%2===0 ? 'dates' : 'numbers'].push(b), a;
}, {numbers:[], dates:[]});

console.log(array)

If performance is important, you'd revert to old-school loops, and two arrays

var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';

var array = string.split(/[,|]/);
var array1 = [];
var array2 = [];

for (var i = array.length; i--;) {
  if (i % 2 === 0) {
    array1.push(array[i]);
  } else {
    array2.push(array[i]);
  }
}

console.log(array1, array2)