This question already has answers here:
How can I convert a comma-separated string to an array?
(19 answers)
Closed 1 year ago.
i have this
string = "Art,fitness"
and i want a array like this
[[Art], [Fitnnes]]
if i do string.spli(',')
i got ["Art", "Fitnnes"]
And is not the output i need, also i try
JSON.parse("[" + string.replace(/'/g, '"') + "]");
but dont work and give me [ 'Art,Fitnnes' ];
i need to do a map before the split to create a new array or there are a simple way to do this
You can do it like this
const string = "Art,fitness"
const result = string.split(",").map(item => [item])
console.log(result)
First, we split() the string on the ,, then we map through the outcome array and return the item in another array.
The below code works well
const string = "Art,fitness";
const newArray = string.split(',').map(str=>[str]);
const string = "Art, fitness";
console.log(string.split(',').map(a => [a]));
Loop over the split values with the .map operator and return them as array.
Instead of splitting the list and mapping each item to an array containing one item, you could alternatively manipulate the input string by converting it to JSON and then parsing the JSON as a two-dimensional array.
First, process all tokens that are a sequence of non-delimiters (ignoring white-space) and wrap them in quotes and brackets (inner-array).
Next, surround the string with brackets (outer-array).
Finally, you can parse the string as JSON data.
const strListToMatrix = listStr =>
JSON.parse(
listStr
.replace(/\s*([^,]+)\s*/g, '["$1"]')
.replace(/(.+)/, '[$1]'));
console.log(strListToMatrix('Art,fitness'));
.as-console-wrapper { top: 0; max-height: 100% !important; }
Related
So, I am fetching values from a database and then i am returning/using them in JSON/javascript as an array for example as shown here
The problem is that I want the sum of the array elements.
I used this code:
var obj1 = JSON.parse(data);
var mar = obj1.march;
var quantite = obj1.quant;
const sum = quantite.reduce((result,number)=> result+number);
console.log(sum);
And here is what I got in the console
I am totally new into JSON and javascript, so, any tips/help would be great for me!
The elements in the array are strings and so, when you use the + operator it concatenates them. You want to parse them first like this:
const sum = quantite.reduce((result,number)=> parseInt(result) + parseInt(number));
Seems that you data contains strings, not int.
You can improve your reduce function:
quantite.reduce((result,number) => parseInt(result)+parseInt(number));
Use the start value of reduce() and make sure number isn't a string when adding it
quantite.reduce((res,num)=> (res + Number(number)),0);
// start value ^^^
i was given a homework problem to be able to create a query string based on certain parameters in an array? I am still fairly new to javascript so have some success with it but would appreciate if someone can check my code please. Thank you to everyone in advance.
I am using forEach to loop through the array to get the values and using string concatenation to get some url. I have made a sample codepen for it.
https://codepen.io/anon/pen/pmRXzg
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
let handler = Object.entries(Person)
handler.forEach(function(element) {
console.log(element)
})
let myUrl = Object.entries(handler).map(key => key + '=' +
handler[key]).join('&')
let visitUrl = "http://someURLString/?" + myUrl
console.log(myUrl)
console.log(visitUrl)
How can i get my final result to look like
someUrlString/?name=Sam,Daisy&food=banana,apple
You can use map() on Object.entries() and then join() entries by = and then join result by &
let Person = {
name: ['Sam','Daisy'],
food: ['banana','Apple']
}
let res = Object.entries(Person).map(x=> x.join('=')).join('&');
console.log(res)
Explanation:
Object.entiries() return an array of arrays. Each array contain key value pair. In this case entries will be [['name', ['Sam','Daisy']], ['food', ['banana','Apple']]].
Now we use map() on array. map() is takes a callback. It that callback first argument(in above case its x) is current element of array through which we are iterating. map() creates new array of same length based on the value returned from callback. In above case value returned is x.join('=')
join() is method which converts array to string by adding a given substring b/w each of them. So when apply join() on
[food , ['banana','Apple']].join('=')
it will become
"food=banana,Apple"
The array ['banana','Apple'] is converted to a string implicitly. So ['banana','Apple'] is banana,Apple
In the last part we get array ["name=Sam,Daisy","food=banana,Apple"] and we join() it by &.
The point is that when we array is converted to string. It returns string in which all elements are separated by ,
You can take advantage of .entries, .map and .join to:
Map [key,value] pairs of Person.
Transform their value to a single string, by eventually manipulating data.
Join them to return the final string.
let Person = {
name: ['Sam', 'Daisy'],
food: ['banana', 'Apple']
}
const res = Object.entries(Person).map(([entryName, entryValues]) => {
return `${entryName}=${entryValues.map(i => i.toLowerCase()).join(',')}`;
}).join('&');
const url = `someUrlString/?${res}`;
console.log(url);
I am getting a set of arrays in string format which looks like
[49,16,135],[51,16,140],[50,18,150]
Now I need to save them in an array of arrays. I tried it like
let array = [];
let str = '[49,16,135],[51,16,140],[50,18,150]';
array = str.split('[]');
console.log(array);
but it is creating only one array including all string as an element while I need to have
array = [[49,16,135],[51,16,140],[50,18,150]]
Add array delimiters to each end of the string, then use JSON.parse:
const str = '[49,16,135],[51,16,140],[50,18,150]';
const json = '[' + str + ']';
const array = JSON.parse(json);
console.log(array);
You are splitting it incorrectly, in the example, it will only split of there is a [] in the string
You can create a valid JSON syntax and parse it instead like so,
let str = '[49,16,135],[51,16,140],[50,18,150]';
let array = JSON.parse(`[${str}]`);
console.log(array);
Another way you could achieve this is by using a Function constructor. This method allows you to "loosely" pass your array.
const strArr = "[49,16,135],[51,16,140],[50,18,150]",
arr = Function(`return [${strArr}]`)();
console.log(arr);
I Have a string like
[ "Basic, JavaScript, PHP, Scala" ]
How to convert it like
[ 'Basic', 'JavaScript', 'PHP', 'Scala' ]
code
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
var a = localStorage.getItem(localKeyChief);
var Item = JSON.stringify(a); // it show like ["Basic, JavaScript, PHP, Scala"]
}
JSON.stringify() returns a String so your question is incorrect. Item is not an Array.
const Item = '["Basic, JavaScript, PHP, Scala"]';
Therefore you should not use it. Instead simply return the array a in your function:
function loadDataToGridChiefComplaint() {
var tHRNo = document.getElementById("lblpthrno").value;
var tOPDNo = document.getElementById("lblptopd").value;
var localKeyChief = tHRNo + '-' + tOPDNo + '-ChiefComplaint';
return localStorage.getItem(localKeyChief); // <-- no use of JSON.stringify()
}
This way loadDataToGridChiefComplaint() is the array ["Basic, JavaScript, PHP, Scala"], it has a single element of type String that you can access with the bracket notation Item[0]:
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0]);
So in order to convert the string Item[0] into an array, use the .split method:
String.split(separator)
The split() method splits a String object into an array of strings by separating the string into substrings, using a specified separator string to determine where to make each split.
MDN Web Docs
const Item = ["Basic, JavaScript, PHP, Scala"];
console.log(Item[0].split(', '));
If you can't modify this function you can use the opposite operation of JSON.stringify which is JSON.parse to convert the string back to an array:
const ItemString = '["Basic, JavaScript, PHP, Scala"]';
ItemArray = JSON.parse(ItemString);
And then use .split (like the previous example) to get the array of strings.
Try this :
var Item = ["Basic, JavaScript, PHP, Scala"];
// Do like this
var array = Item[0].split(', '); // Split with Comma and space(for trim whitespace)
// Or Like this
var array = Item[0].split(',').map(i => i.trim()) // Split with comma and use map to trim whitespace
console.log(array);
I'm passing myself a string of results from php by ajax that I would like to put into a two dimensional array in JavaScript
The string looks like: value1^*value2^*value3^*value4***value1^*value2^*value3^*value4
I would like to split the values by '^*' into the first row of the dimensional array, then the next row would be after the '***'
Desired array:
var Text = [['value1', 'value2','value3','value4'],[value1','value2','value3','value4']];
You can use split() to split your string into an array of strings ( value1^*value2^*value3^*value4 and value1^*value2^*value3^*value4 ), after that you will need map() to creates a new arrays inside each array which we get before.
Example:
var str = "value1^*value2^*value3^*value4***value1^*value2^*value3^*value4"
str = str.split('***')
str = str.map((value) => value.split('^*'))
console.log(str)
You can do something like that
var input = "value1^*value2^*value3^*value4***value5^*value6^*value7^*value8";
var res = input.split('***').map(function(rowValues){
return rowValues.split('^*');
})
console.log(res);