Split an array cause an error: not a function - javascript

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

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)

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 = [];
var array_s = [];
string.split('|').forEach(function(el){
var temp = el.split(",");
array_dt.push(temp[0]);
array_s.push(temp[1]);
});
console.log(array_dt);
console.log(array_s);

Just do it one step at a time - split by pipes first, leaving you with items that look like 2016-08-08,63. Then for each one of those, split by comma, and insert the values into your two output arrays.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var arr = string.split("|");
var array_dt = [];
var array_s = [];
arr.forEach(function(item) {
var x = item.split(",");
array_dt.push(x[0]);
array_s.push(x[1]);
});

Related

How to extract specific words from a string with some patterns?

I am trying to extract some strings from a word with some pattern like -
"38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"
how will I extract all word between - separately, means first word before - and then second word between - and - and so on...
string = "38384-1-page1-2222";
string.substr(0, string.indexof("-")); //return 38384
But how will I extract 1, page1 and 2222 all the words separately?
The javascript function str.split(separator) split the string by the given separator and it returns an array of all the splited string. REF Here
Here is an example following your question :
var string = "38384-1-page1-2222";
var separator = "-";
var separated = string.split(separator);
var firstString = separated[0]; // will be '38384'
var secondString = separated[1]; // will be '1'
var thirdString = separated[2]; // will be 'page1'
/* And So on ... */
Hope this can help
Use String.prototype.split() to get your string into array
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var resultArray = [];
for (let i = 0; i < words.length;i++) {
let temp = words[i];
resultArray = pushArray(temp.split("-"), resultArray)
}
console.log(resultArray)
function pushArray (inputArray, output) {
for (let i = 0; i < inputArray.length;i++) {
output.push(inputArray[i]);
}
return output;
}
Or simply use Array.prototype.reduce()
var words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
var result = words.reduce((previousValue, currentValue) => previousValue.concat(currentValue.split("-")), [])
console.log(result)
You can use regex /[^-]+/g
const words = ["38384-1-page1-2222", "1-22-page33-02", "99-222-frontpage-111"];
console.log(words.map(v=>v.match(/[^-]+/g)).flat())

How can I convert string to a array?

I have the following array:
var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
How can I convert it to an array like this:
var array = ['Daniel','Alguien','2009',2014];
You can do it this way:
var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
var array = mystr.match(/\[.+?\]/g).map(function(value){ // searches for values in []
return value.replace(/[\[\]]/g,""); // removes []
});
Try to use following code , as you can see the string is split by comma and then using regular expressions the necessary part has been pushed to new array
var mystr = "Name[Daniel],Name2[Alguien],Date[2009],Date[2014]";
var array = mystr.split(",");
re = /\[(.*)\]/;
var newArray = [];
for (var i = 0; i < array.length; i++) {
newArray.push(array[i].match(re)[1]);
}
newArray = ['Daniel', 'Alguien', '2009', 2014];

Extract specific substring using javascript?

If I have the following string:
mickey mouse WITH friend:goofy WITH pet:pluto
What is the best way in javascript to take that string and extract out all the "key:value" pairs into some object variable? The colon is the separator. Though I may or may not be able to guarantee the WITH will be there.
var array = str.match(/\w+\:\w+/g);
Then split each item in array using ":", to get the key value pairs.
Here is the code:
function getObject(str) {
var ar = str.match(/\w+\:\w+/g);
var outObj = {};
for (var i=0; i < ar.length; i++) {
var item = ar[i];
var s = item.split(":");
outObj[s[0]] = s[1];
}
return outObj;
}
myString.split(/\s+/).reduce(function(map, str) {
var parts = str.split(":");
if (parts.length > 1)
map[parts.shift()] = parts.join(":");
return map;
}, {});
Maybe something like
"mickey WITH friend:goofy WITH pet:pluto".split(":")
it will return the array, then Looping over the array.
The string pattern has to be consistent in one or the other way atleast.
Use split function of javascript and split by the word that occurs in common(our say space Atleast)
Then you need to split each of those by using : as key, and get the required values into an object.
Hope that's what you were long for.
You can do it this way for example:
var myString = "mickey WITH friend:goofy WITH pet:pluto";
function someName(str, separator) {
var arr = str.split(" "),
arr2 = [],
obj = {};
for(var i = 0, ilen = arr.length; i < ilen; i++) {
if ( arr[i].indexOf(separator) !== -1 ) {
arr2 = arr[i].split(separator);
obj[arr2[0]] = arr2[1];
}
}
return obj;
}
var x = someName(myString, ":");
console.log(x);

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.

How do I divide a complex string into 3 seperate arrays?

Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values
mystring = 4|black|cat, 7|red|dog, 12|blue|fish
Here's where I want to be:
I want to end up with three arrays.
array1=("4","7","12")
array2=("black","red","blue")
array3=("cat","dog","fish")
I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.
I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:
var arr1 = [], arr2 = [], arr3 = [],
mystring = "4|black|cat, 7|red|dog, 12|blue|fish";
mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) {
arr1.push($1);
arr2.push($2);
arr3.push($3);
});
Example
You want to use the split() method :
var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]
//etc...
Like this?:
var values = mystring.split(',');
var arrays = new Array();
for(var i=0; i < values.length; i++) {
var parts = values[i].split('|');
for(var j = 0; j < parts.length;j++) {
if(!arrays[j]) {
arrays[j] = new Array();
}
arrays[j].push(parts[j]);
}
}
Will give you an array that contains those three arrays.
var str = '4|black|cat, 7|red|dog, 12|blue|fish';
var tmp = str.split(',');
var firstArray = Array();
var secondArray = Array();
var thirdArray = Array();
for( var i in tmp ){
var splitted = tmp[i].split('|');
//alert(true);
firstArray[i]=splitted[0];
secondArray[i]=splitted[1];
thirdArray[i]=splitted[2];
}

Categories

Resources