How to clean , from a given string? - javascript

I have data like this.
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for( var i = 0 ; i <abc.length - 1;i++){
stub[key[j]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
I would like to get those values arranges in form of array of object having those 3 keys:
output should be:
abc = [{"name": "paul", "value": "2000","acc":"12sc21"},{"name":"logan","value":"123","acc":"21sdf34"},{"name":"vfsarwe","value":"456456","acc":"32fd23"}];
but not able to get the desired output. this output only comes when string don't have ,,,,,, in starting. But the data i'm getting is sometimes having ,,,,, in stating.

You can use abc.replace(/(^[,\s]+)/g, '') to remove leading commas or whitespace from the String. Your for loop is also not running for long enough; it is looping until there is only one element left in the Array and then stopping.
Change
for(var i = 0 ; i < abc.length-1; i++)
To
for(var i = 0 ; i < abc.length; i++)
var abc =",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
abc = abc.replace(/(^[,\s]+)|([,\s]+$)/g, '').split(",");
let stub={};
var results=[];
var key=["name","value","acc"];
var i=0;
var j=0;
for(var i = 0 ; i < abc.length; i++){
stub[key[j]]=abc[i];
j++
if(j==3){
results.push(stub);
stub={};
j=0;
}
}
abc = results;
console.log(abc);

You can use .replace(/^\,+/, '') to remove all leading commas, then split by comma to get an array, then loop over this array using 3 as step and construct your results:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
Demo:
var abc = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var arr = abc.replace(/^\,+/, '').split(",");
var results = [];
for (var i = 0; i < arr.length; i = i + 3) {
results.push({
"name": arr[i],
"value": arr[i + 1],
"acc": arr[i + 2]
});
}
console.log(results);

You are on the right track with splitting your data on ,. You can then split the data in to chunks of 3, and from there map each chunk to a dict.
var data = ",,,,,,,,,,,,,,,paul,2000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var split = data.split(",");
var chunked = [];
while (split.length) {
chunked.push(split.splice(0,3));
}
var res = chunked.map((i) => {
if (!i[0] || !i[1] || !i[2]) {
return null;
}
return {
name: i[0],
value: i[1],
acc: i[2]
};
}).filter((i) => i !== null);
console.log(res);

You can use:
abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(',');
The regEx replaces removes the data that you are not interested in before performing the split.
or
abc.split(',').filter(Boolean);
The filter(Boolean) will remove the items from the array that could be the equivalent of false once the array has been instantiated.
EDIT:
var abc =",,,,,,,,,,,,,,,paul,2,000,12sc21,logan,123,21sdf34,vfsarwe,456456,32fd23";
var array = abc.replace(/,+/g, ',').replace(/^,|,$/g, '').split(/,([0-9,]+),/);
array = array.filter(Boolean).reduce(function(acc, item) {
if (item.match(/^[0-9,]+$/)) {
acc.push(item);
} else {
acc = acc.concat(item.split(','));
}
return acc;
}, []);

Related

JavaScript Split String into multiple Arrays

I have a comma separated string in JavaScript that I want to separate into mutiple arrays, for each column but I want to ignore the first couple of lines. So for instance I want to convert the following string,
let data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3";
into arrays like the following.
["A", "1", "1"]
["B", "2", "2"]
["C", "3", "3"]
EDIT
Ths is my initial solution that I tried. Like it works but it's not really a nice solution:/
for (let i = 1; i < out.length; i++)
{
let arr = out[i].split(',');
if (i === 1)
{
for (let j = 0; j < columns; j++)
{
let col = "arr" + j;
console.log(col);
obj[col] = [arr[j]];
}
console.log(obj);
}
else
{
for (let j = 0; j < columns; j++)
{
let col = "arr" + j;
let val = arr[j];
if (j !== "")
{
obj[col].push(val);
}
}
}
}
I should point out that I eventually want to create a map of the letters to corresponding array of numbers and I won't know what the key value will be. So I'll be trying to get something like the following,
"A": ["1", "1"]
"B": ["2", "2"]
"C": ["3", "3"]
You could split by ',\n,' for getting lines and for the items split by comma. Then omit the first two arrays.
var data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3",
result = data.split(',\n,').map(s => s.split(',')).slice(2);
console.log(result);
for your expected result you first have to split a string by ',' and then run for loop on a resulted array and inside that convert, you alphabet with a number and compare numbers if match found than push it into a respective array.
like below code
var datArray= [];
a = [];
b = [];
c = [];
let data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3";
datArray = data.split(',');
for(var i = 0; i < datArray.length; i++) {
if(datArray[i] == 'A' || datArray[i] == 1) {
a.push(datArray[i]);
} else if(datArray[i] == 'B' || datArray[i] == 2) {
b.push(datArray[i]);
} else if(datArray[i] == 'C' || datArray[i] == 3) {
c.push(datArray[i]);
}
}
console.log(a);
console.log(b);
console.log(c);
this is one of the way you can do...
This method is not hard coded ! With this method you can handle :
ABCDEF.... , 1 2 3 4 5 6 ...
We will split for first action. Then detect Not A Number function isNaN to detect A B C .
Array helpers :
var notNumber = [];
var numbers = [];
to store data .
On the end generate your results arrays !
Try this :
var data = "test,data,\n,ignore,this,\n,A,B,C,\n,1,2,3,\n,1,2,3";
var handler = data.split(",");
var preventFlag = true;
var countNaN = 0;
var notNumber = [];
var numbers = [];
//console.log(handler);
for (var x = 0;x < handler.length;x++) {
var currentData = handler[x];
if (preventFlag == false) {
if ( isNaN(currentData) ) {
notNumber.push(currentData);
}
else {
if (currentData != "\n") {
numbers.push(currentData);
}
}
}
if (currentData == "this"){
preventFlag = false;
}
}
//console.log(notNumber)
//console.log(numbers)
for (var z = 0; z < notNumber.length;z++) {
window["result" + z] = [];
window["result" + z].push(notNumber[z]);
//console.log(window["result0"])
window["result" + z].push(numbers[z])
window["result" + z].push(numbers[z + (notNumber.length) ])
}
// GENERATE RESULT ARRAY
console.log(window["result0"]);
console.log(window["result1"]);
console.log(window["result2"]);
//["A", "1", "1"]
//["B", "2", "2"]
//["C", "3", "3"]

JavaScript - Converting URL like string params to an array

I have a string like this:
var str = 'My_Type_1=SSD&My_Value_1=16GB&My_Category_1=Disk Capacity&My_Type_2=Sony
&My_Value_2=PS4&My_Category_2=Console&My_rowOrder=2,1';
The string mostly has 3 parts except the last key:
Part 1 -> My - is a Common Prefix
Part 2 -> Type or Value or Category and it can keep changing
Part 3 -> It's a numeric value binding Part 1, Part 2 and Part 3 like Spreadsheet row.
The last key is always called
My_rowOrder and it's a comma delimeted value. It specifies how to construct the output array.
In the above example, 2,1 means a key value pair of
My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console should be the first in the output array.
Using JavaScript, I would like to parse the string and create an array out of it, such that the output is:
Array
(
[ 0 ] => Array
(
[Type] => Sony
[Value] => PS4
[Category] => Console
[Row] => 2
)
[ 1 ] => Array
(
[Type] => SSD
[Value] => 16GB
[Category] => Disk Capacity
[Row] => 1
)
)
How can I do this? I am partially able to do it this way:
function StringToArray(string) {
var request = {};
var pairs = string.split('&');
for (var i = 0; i < pairs.length-1; i++) {
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//I think I am in the right track, but need assistance
}
Your example output uses associative arrays, which JavaScript doesn't have, but you can use an array of objects instead.
This example outputs an array of objects, in the order specified by the rowOrder parameter. It trims the prefix (defined by prefix), and also trims the row number from the end of the key.
This will also work with the parameters in any order - e.g. you can mix them and it will parse as necessary, and the rowOrder parameter can appear anywhere in the string (doesn't have to be at the end).
Demo
function StringToArray(string) {
var prefix = 'My_'; // set the prefix
var output = [], request = [];
var pairs = string.split('&');
var order;
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
if (pair[0].replace(prefix, '') == 'rowOrder') {
order = pair[1];
} else {
var key = decodeURIComponent(pair[0]);
var pos = key.lastIndexOf('_');
var trimmedKey = key.substring(0, pos).replace(prefix, '');
var row = key.substring(pos + 1);
var value = decodeURIComponent(pair[1]);
var found = false;
for (var j = 0; j < output.length; j++) {
if (output[j].Row == row) {
output[j][trimmedKey] = value;
found = true;
}
}
if (!found) {
var obj = { 'Row': row };
obj[trimmedKey] = value;
output.push(obj);
}
}
}
// do the ordering based on the rowOrder parameter
var orderList = order.split(",");
for(var k=0; k<orderList.length; k++){
for(var l=0; l<output.length; l++){
if(output[l].Row == orderList[k]){
request.push(output[l]);
break;
}
}
}
return request;
}
Outputs an array of objects in the order specified by the My_rowOrder parameter:
[
{
Row: "2",
Type: "Sony",
Value: "PS4",
Category: "Console"
},
{
Row: "1",
Type: "SSD",
Value: "16GB",
Category: "Disk Capacity"
}
]
This may works for you...
<script>
var data = "My_Type_2=Sony&My_Value_2=PS4&My_Category_2=Console";
var array = new Array();
alert(JSON.stringify(URLToArray(data)));
function URLToArray(url) {
var request = {};
var pairs = url.substring(url.indexOf('?') + 1).split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
return request;
}
</script>
Try this:
function StringToArray(string) {
var request = [[],[]];
var pairs = string.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
request[pair[0].slice(-1)-1][decodeURIComponent(pair[0])] = decodeURIComponent(pair[1]);
}
//console.log(request)
}

rearrange Array according to values order of another Array

I have two arrays like below
var arr = ["x", "y", "z", "a", "b", "c"];
var tgtArr = [{val:"a"}, {val:"b"}]; It does not need to be as lengthy as Array `arr`
This is what I have tried
var dest = new Array(arr.length);
for(var i = 0; i < arr.length; i++){
for(var k = 0; k < tgtArr.length; k++){
dest[i] = dest[i] || [];
if(tgtArr[k].val == arr[i]){
dest[i] = arr[i];
}
}
}
console.log(dest);
My Expected output is (for above tgtArr value)
[{}, {}, {}, {val:"a"}, {val:"b"}, {}];
if tgtArr is empty Array
[{},{},{},{},{},{}]
Here is the fiddle. Any alternative for this, it seems not a good way to me as I am iterating through the entire array everytime.
Short:
var result = arr.map(function(x) {
return tgtArr.some(function(o) { return o.val == x; }) ? {val:x} : {};
});
This is more efficient:
var set = {};
tgtArr.forEach(function(obj, i) {
set[obj.val] = true;
});
var result = arr.map(function(x) {
return x in set ? {val:x} : {};
});
This is the same as Paul's answer, but with a loop instead of map. It collects the keys first based on the val property, then creates a new array either with empty objects if the key isn't in tgtArr, or copies a reference to the object from tgtArr if it is:
function newArray(arr, tgtArr) {
var keys = {},
i = tgtArr.length,
j = arr.length,
newArr = [];
// Get keys
while (i--) keys[tgtArr[i].val] = tgtArr[i];
// Make new array
while (j--) newArr[j] = arr[j] in keys? keys[arr[j]] : {};
return newArr;
}
It should be efficient as it only traverses each array once.
var dest = new Array(arr.length);
for(var i = 0; i < arr.length; i++){
dest[i] = {}
for(var k = 0; k < tgtArr.length; k++){
if(tgtArr[k].val == arr[i]){
dest[i] = tgtArr[k];
}
}
}
console.log(dest);
I like using map rather than loops for this kind of thing (Fiddle):
var result = arr.map(function(x) {
var match = tgtArr.filter(function(y) {
return y.val == x;
});
if (match.length == 1) return match[0];
else return {};
});
This is a possibly inefficient, in that it traverses tgtArr for every item in arr, so O(n*m). If needed, you could fix that by pre-processing tgtArr and converting it to a hash map (Fiddle). This way you've got an O(n+m) algorithm (traverse each array once):
var tgtMap = {};
tgtArr.forEach(function(x) { tgtMap[x.val] = x; })
var result = arr.map(function(x) {
var match = tgtMap[x];
return match || {};
});
var tmp = {};
for (var i = 0; i < tgtArr.length; i++) {
tmp[tgtArr[i].val] = i;
}
var dest = [];
for (var i = 0; i < arr.length; i++) {
var obj= tmp[arr[i]] === undefined ? {} : tgtArr[tmp[arr[i]]];
dest.push(obj);
}
DEMO

Adding an array of values

This is the json data I have
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
How can I use jQuery to get the result as
"Result" : ["1", "3","6","10", "15"]
var myArray = [];
var data = myArray.data
for ( var i = 0; i < data.length; i = i + 1 ) {
val = i == 0 ? 0 : myArray[i-1]
myArray.push(data[i]+val)
}
console.log(myArray)
Unless the data is part of an DOM object, I don't see the point of using jQuery.
var myData =
{
"data" :
{
"Count" : ["1","2","3","4", "5"]
}
}
var countAry = myData.data.Count;
var results = new Array(countAry.length);
for (var i = 0, il = countAry.length; i < il; i++) {
results[i] = Number(countAry[i]) + (results[i - 1] || 0);
}
myData.data.Results = results;
console.log(myData);
No need for jQuery, a primitive loop will do that:
// Either
var obj = {"data":{"Count":["1","2","3","4","5"]}}
// or
var obj = JSON.parse(jsonString);
var arr = obj.data.Count,
res = [],
acc = 0;
for (var i=0; i<arr.length; i++)
res[i] = String(acc += Number(arr[i]));
obj.data.Result = res;
Or, if you only want to add the counts to their previous (single) one only, use
for (var i=0; i<arr.length; i++)
res[i] = String(+arr[i] + (i && +arr[i-1]));
If you can use the ECMAScript 5 Array methods: Assuming json is your json data...
var sum = 0,
count = JSON.parse(json).data.Count.map(function(i) {
return parseInt(i, 10) + sum;
});

group array division

this code http://jsfiddle.net/minagabriel/5MQ77/
var flowShadeBigArray =[] ;
var x = [7, 411, 780]
var y = [286, 712, 1058]
for( var i = 0 ; i< x.length;i++){
for(var index = x[i]; index <= y[i] ; index++ ){
var temp = [] ;
temp.push(index) ;
flowShadeBigArray.push(temp);
}
}
console.log(JSON.stringify(flowShadeBigArray));
generate the following array
[[7],[8],[9],[10],[11],[12],[13],[14]................[1056],[1057],[1058]]
i want to create a three arrays inside flowShadeBigArray and have the [x[i] ... y[i] ]
grouped together:
example
[ [ [7]....[286] ] , [ [411]...[712] ] ,[ [780]...[1058] ] ]
NOTE i still need to keep each of these numbers as an array so i can use it an an index for something else
THANKS
Just move the temp initialization to the first loop, before the second, and the .push() to the first loop after the second (or before, doesn't matter).
var flowShadeBigArray = [];
var x = [7, 411, 780]
var y = [286, 712, 1058]
for (var i = 0; i < x.length; i++) {
var temp = [];
for (var index = x[i]; index <= y[i]; index++) {
temp.push(index);
}
flowShadeBigArray.push(temp);
}
http://jsfiddle.net/5MQ77/1/
If each individual number belongs in its own Array, then change this:
flowShadeBigArray.push(temp);
to this:
flowShadeBigArray.push([temp]);
-edited
function range(from, to) {
var arr = [];
while (from <= to) {
arr.push([i++]);
}
return arr;
}
var result = [];
for (var i=0; i<x.length; i++) {
result.push(range(x[i], y[i]));
}

Categories