How can I convert string to a array? - javascript

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];

Related

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
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]);
});

Remove duplicate in a string - javascript

I have a string in javascript where there are a lot of duplicates. For example I have:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
What can I do to delete duplicates and to get for example x="Int32,Double"?
With Set and Array.from this is pretty easy:
Array.from(new Set(x.split(','))).toString()
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
x = Array.from(new Set(x.split(','))).toString();
document.write(x);
If you have to support current browsers, you can split the array and then filter it
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
var arr = x.split(',');
x = arr.filter(function(value, index, self) {
return self.indexOf(value) === index;
}).join(',');
document.body.innerHTML = x;
Use new js syntax remove Dupicate from a string.
String.prototype.removeDuplicate = Function() {
const set = new Set(this.split(','))
return [...set].join(',')
}
x.removeDuplicate()
function myFunction(str) {
var result = "";
var freq = {};
for(i=0;i<str.length;i++){
let char = str[i];
if(freq[char]) {
freq[char]++;
} else {
freq[char] =1
result = result+char;
}
}
return result;
}
That is a more readable and better parameterized solution:
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
var removeDup = [...new Set(x.split(","))].join(",");
//result "Int32,Double"
Check This out -
removeDuplicates() function takes a string as an argument and then the string split function which is an inbuilt function splits it into an array of single characters. Then the arr2 array which is empty at beginning, a forEach loop checks for every element in the arr2 - if the arr2 has the element it will not push the character in it, otherwise it will push. So the final array returned is with unique elements. Finally we join the array with the join() method to make it a string.
const removeDuplicates = (str) => {
const arr = str.split("");
const arr2 = [];
arr.forEach((el, i) => {
if (!arr2.includes(el)) {
arr2.push(el);
}
});
return arr2.join("").replace(",", "").replace("", " ");
};
console.log(removeDuplicates( "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"));
Its simple just remove duplicates in string using new Set and join them.
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
console.log([...new Set(x)].join(""));
function removeDups(s) {
let charArray = s.split("");
for (let i = 0; i < charArray.length; i++) {
for (let j = i + 1; j < charArray.length; j++)
if (charArray[i] == charArray[j]) {
charArray.splice(j, 1);
j--;
}
}
return charArray.join("");
}
console.log(removeDups("Int32,Int32,Int32,InInt32,Int32,Double,Double,Double"));
You can use Set()
const result = Array.from(new Set(x)).join('')
var x = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double"
const result = Array.from(new Set(x)).join('')
console.log(result)
you can use the replaceAll function:
let str = "/Courses/"
let newStr = str.replaceAll('/', '')
console.log(newStr) // result -> Courses
function removeDuplicate(x)
{
var a = x.split(',');
var x2 = [];
for (var i in a)
if(x2.indexOf(a[i]) == -1) x2.push(a[i])
return x2.join(',');
}
const str = "Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Int32,Double,Double,Double";
const usingSpread = [...str]
const duplicatesRemove = [...new Set(usingSpread)]
const string = duplicatesRemove.join("")
console.log("After removing duplicates: " + string)
STEPS
convert string to character array using spread operator
new Set will implicitly remove duplicate character
convert character array to string using join("") method

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);

Reorganize array of arrays to array of hashes and convert to JSON

I have the following array
var arr=[[10,20,30],[12,21,33],[13,23,35]];
How can I convert that array to JSON.
Desired result
myJSONarr=[
{"x":10 ,"y":20,"z":30},
{"x":12 ,"y":21,"z":33},
{"x":13, "y":23,"z":35}
];
I'm guessing I will have to define sting array
var objArray=["x","y","z"];
and do loop over these two values with the eval() function.
Any help is greatly appreciated.
if you use jquery:
var arr=[[10,20,30],[12,21,33],[13,23,35]],
myjson = JSON.stringify($.map(arr,function(a){return {x:a[0],y:a[1],z:a[2]}}));
http://jsfiddle.net/herostwist/yDRwh/
if you use prototype:
var myjson = JSON.stringify([[10,20,30],[12,21,33],[13,23,35]].map(function(a){
return {x:a[0],y:a[1],z:a[2]}}));
http://jsfiddle.net/herostwist/yDRwh/1/
My version. Edit: I didn't twig objArray wasn't part of the problem, but the OP's suggestion as part of the solution. Oh well, I like it anyway.
var arr=[[10,20,30],[12,21,33],[13,23,35]];
var objArray=["x","y","z"];
var myJSONarr = [];
for (var idx = 0; idx != arr.length; idx++) {
var row = {};
for (var idx2 = 0; idx2 != objArray.length; idx2++) {
row[objArray[idx2]] = arr[idx][idx2];
}
myJSONarr.push(row);
}
alert(JSON.stringify(myJSONarr));
Many different answers, here's another:
http://jsfiddle.net/Vecqc/
<textarea id="text" style="width: 100%;"></textarea>
var arr = [[10,20,30],[12,21,33],[13,23,35]];
var stringify = [];
for (var i = 0; i < arr.length; i++) {
stringify[i] = {'x':arr[i][0],'y':arr[i][0],'z':arr[i][0]};
}
document.getElementById('text').value = JSON.stringify(stringify);
Assuming you just want to map the values to JavaScript objects†:
var objs = [];
for(var i = 0, l = arr.length; i < l; i++) {
var p = arr[i];
objs.push({x: p[0], y: p[1], z: p[2]});
}
If you really want to create a JSON string, then you can pass this array to JSON.stringify. JSON is available in all modern browser and can be loaded for older ones.
†: Why am I assuming here? Because people confuse JSON with JavaScript object literals. In your code, myJSONarr is not JSON. It is an array of JS objects. It would be JSON if the data would be contained in a string:
var myJSONarr = '[{"x":10, "y":20, "z":30}, ...]';
JSON != JavaScript object
What you are describing is not merely a JSON conversion. You actually have an array full of three element arrays of numbers, and what you are wanting is JSON for an array of hashes where each triplet becomes a hash over "x","y","z".
Anyway, if you want a simple .toJSON() function, Prototype.js includes a .toJSON() function onto most objects that makes it really easy.
http://www.prototypejs.org/learn/json
Untested...
var arr=[[10,20,30],[12,21,33],[13,23,35]];
var myarrOfXYZ = arr.collect(function(T){ return $H({ x: T[0], y: T[1], z: T[2] }) });
var myJSON = myarrOfXYZ.toJSON();
Note that prototype also provides a function "zip" that can be used on line 2 instead of $H
Just loop through the array and create a string from each array inside it, then join the strings to form the JSON string:
var items = [];
for (var i = 0; i < arr.length; i++) {
items.push('{"x":'+arr[i][0]+',"y":'+arr[i][1]+',"z":'+arr[i][2]+'}');
}
var myJSONarr = '[' + items.join(',') + ']';
First:
var arr = [[10,20,30], [12,21,33], [13,23,35]];
var arr2 = [];
for (var i in arr) {
var a = arr[i];
arr2.push({
x: a[0],
y: a[1],
z: a[2]
});
}
Or, using higher-order functions:
var labels = ["x", "y", "z"];
var arr = [[10,20,30], [12,21,33], [13,23,35]];
var arr2 = arr.map(function(a) {
return a.reduce(function(prev, curr, i) {
prev[labels[i]] = curr;
return prev;
}, {});
});
Then directly convert the new array to JSON.

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