Is there any method to remove unnecessary spaces of output array. When I run the code there is space in between comma and integer and also integer and bracket.
var arr = [1,2,3,4,5];
console.log(arr);
output
[ 1, 2, 3, 4, 5 ]
desire output
[1,2,3,4,5]
console.log or console.log is a basic tool function which have very defined behavior that you can't change.
The only thing you can do is to use a trick. console.log handle differently the string and the arrays, so you can transform your array before to display it.
Moreover they didn't made it possible to influence the display because there is no purpose to it. What are you trying to achieve using console.log in your app?
console.log had been created in order to display debug messages, not to display data to regular users.
For example in node.js, in order to display data to your user in console, use of :
process.stdout.write(your_string_in_your_own_format);
const arr = [1,2,3,4,5];
// Basic array
console.log(arr);
// Transform the arr into a string
console.log(JSON.stringify(arr));
Related
Sounds way more confusing than it actually is, but it is simple given an example:
Let's say I have an array like this - [1, 2, 3, 4, 5]
I want the numbers 2, 3 and 4 in their own array like this - [2, 3, 4]
One detail is that the array is completely random! It is all user inputted so I use keywords to find the section I want, like this - ["cmd", "|arg", "stuff", "blah", "|end"]
For this example I would like an array of the items between the keywords |arg and |end that looks like this - ["stuff", "blah"]
I have already found the position in the array of the two keywords but how would I go about making an array of the items between these keywords?
I have tried splicing and I have tried for, but for is not allowed in the game I am coding for and I just cannot seem to find out how to splice it. There has to be a better way and I am not sure what the Method would be called if there even is a Method that can accomplish this.
I don't have any real code to show, as it would be a complete and utter mess if I show it
Just started learning javascript 3 days ago
If you first check to see if that the array contains both values, then you can slice the array into another result array.
let ar = ["cmd", "|arg", "stuff", "blah", "|end"];
let arRes = [];
if(ar.includes("|arg") && ar.includes("|end")){
let idx1 = ar.indexOf("|arg") + 1;
let idx2 = ar.indexOf("|end");
arRes = ar.slice(idx1, idx2)
}
console.log(arRes)
I am working on dynamically generating XML for printing labels. I have an array of values generated with map, the format of this array should end up as such:
[[val1a, val1b, val1c],[val2a,val2b,val2c],[val3a,val3b,val3c]]
I am unable to log to the browser console in this application, so must use provided logging APIs to view the actual values of the array at any given point. The format presented by logging is as such:
val1a,val1b,val1c,val2a...
The values are generated like so:
for(var i = 0; i < lines; i++) {
for(var j = 0; j < quantity; j++){
smCnts.push([i]);
}
}
Where i is the line number of the specific "record", and j is iterating over the quantity, pushing the line number to the array smCnts. Resulting in a dataset like this (assuming line 1 has a quantity of 3, and line 2 has a quantity of 2 etc.):
[[1], [1], [1], [2], [2], [3]]
This array is then mapped using a function that gets values from the lines:
var smLbls = smCnts.map(getData);
Resulting in something like the first array listed in this question.
The problem results when trying to index the array for a specific value:
var foo = smLbls[1];
This returns nothing, I don't even know if it returns null as the logging api returns only: .
However, logging smLbls returns the first mentioned array as described in the second code snippet. What would be causing this issue? I need to be able to get the index of the index of an array like so:
var bar = smLbls[1][3];
Everything else is working as expected, I am just unable to access this data for whatever reason, maybe I am not understanding JavaScript fully?
I am unable to log to the browser console in this application, so must use provided logging APIs to view the actual values of the array at any given point. The format presented by logging is as such:
My advice, use the logs to extract a snapshot of your data:
nlapiLogExecution('debug', 'sample', JSON.stringify(data));
...and work in the browser.
Array input: [["test","test"],["test2","test"],["test2","test2"],["test","test2"]]
Array output: ["test test","test2 test","test2 test2","test test2"]
I'm able to obtain this output with:
output = input.join("|").replace(/,/g," ").toString().split("|")
However, I don't really like this workaround because:
It seems unnatural
If one of the arrays contains a comma itself, it will be also
removed
If one of the arrays contains a pipe itself, the split will be not as expected
How can I get the output without those handicaps?
Instead of joining the outer array, you can use map to join each inner array separately:
var arr = [["test","test"],["test2","test"],["test2","test2"],["test","test2"]];
var output = arr.map(subarr => subarr.join(' '));
I send a php array like:
$var = array (
0=> 4,
1=> 6,
2=> 8,
...
as json_encode($var); into the uri and then I receive it into javascript file is still ok here but when I push it into new array like this :
this.patg.push(attd);
Is inserted like this below .
var attds = ["4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606"]
I know I have to find the problem. but
Questions:
could you please tell me why this could happends or help me to deal with it.
but in any case just for knowledge . how you would add the extra " " surrounding the , that i miss to be an array , or is that crazy idea to fix this?
If you are receiving a string value and you want to use it as an array of integers you should split it into an array first:
var receivedData = "4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606";
var dataArray = receivedData.split(",");
Afterwards you can use it with another array, however be aware that if you already have a defined array into which you want to push the dataArray you shouldn't push but concat instead.
In other words if you have:
var previousArray = [1,2,3];
previousArray.push(dataArray);
You will get
[1,2,3,[4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]]
meaning that the whole array is pushed onto the 4th position of previousArray.
If, on the other hand, you concat the arrays will merge:
var previousArray = [1,2,3];
previousArray.concat(dataArray);
[1,2,3,4,6,7,8,9,5558,5560,5573,5574,5586,5589,5606]
Source: http://www.w3schools.com/jsref/jsref_concat_array.asp
I am new to javascript programming and i am stuck with data-attribute retrieval.
The below link is a bit useful for people using jQuery
store and retrieve javascript arrays into and from HTML5 data attributes
I would like to do the same with vanilla js. With the help of custom data-attributes i would like to create objects & array.
<div id="getAnimation"
data-r="564"
data-c="96"
data-custom="x:0;y:0;z:0;rotationX:0;rotationY:0;rotationZ:0;scaleX:0.75;scaleY:0.75; skewX:0;skewY:0;opacity:0;transformPerspective:600;transformOrigin:50% 50%;"
data-s="700"
data-st="1400"
</div>
Do HTML5 custom data attributes “work” in IE 6?
The above link helps in getting data attributes very well but how can be filter the string in data-custom or straight create an object of data-custom.
If someone know a library to do this please let me know
Here are a couple quick functions which will let you store, retrieve and delete any JSON-able data to a data attribute
function setData(node, data_name, data_value) {
node.dataset[data_name] = JSON.stringify(data_value);
}
function getData(node, data_name) {
return JSON.parse(node.dataset[data_name]);
}
function delData(node, data_name) {
return delete node.dataset[data_name];
}
Then to write an Array to #getAnimation in data-fizz
// variables to use
var elm = document.getElementById('getAnimation'),
foo = [1, 2, 3, 'a', 'b', 'c'];
// store it
setData(elm, 'fizz', foo);
// retrieve it
var bar = getData(elm, 'fizz');
// look what we have
console.log(bar); // [1, 2, 3, "a", "b", "c"]
Requires IE 11+ because I use node.dataset, if you change this to the methods node.setAttribute, node.getAttribute and node.removeAttribute as used, the requirement drops to IE 8+ because of the JSON.stringify and JSON.parse
That particular example is quite straight forward: It's a series of name:value pairs separated with semicolons. So you can get an array of the pairs using split, and then get the name and valid separate using split again. If you want to create properties on an object using those names and values, you can do that with bracketed notation:
// Get the value
var val = theElement.getAttribute("data-custom");
// Split it into fields on `;` (with optional whitespace on either side)
var fields = val.split(/\s*;\s*/);
// Create a blank object
var obj = {};
// Loop through the fields, creating object properties:
fields.forEach(function(field) {
// Split the field on :, again with optional whitespace either side
var parts = field.split(/\s*:\s*/);
// Create a property on the object using the name, and assigning the value
obj[parts[0]] = parts[1];
});
I'm using String#split there, giving it a regular expression to tell it where the split up the string.
In the resulting object, with just the code above, the property values will all be strings. For instance, obj.scaleX will be the string "0.75". If you need them as numbers, you can convert them to numbers in any of several ways:
parseFloat, which will convert as many characters as it can but ignore trailing characters. so parseFloat("0.75foo") is 0.75, not an error.
Number, which will not be tolerant like parseFloat, Number("0.75foo") is NaN, not 0.75.
Applying any mathematical operator, the unary + is common: +"0.75" is 0.75.
So rather than just grabbing the values as strings, we could check to see if they look like they might be numbers and convert them if so:
// Loop through the fields, creating object properties:
fields.forEach(function(field) {
// Split the field on :, again with optional whitespace either side
var parts = field.split(/\s*:\s*/);
// Does the value look like a number?
if (/(?:^\d+$)|(?:^\d+\.\d+$)/.test(parts[1])) {
// Yes
obj[parts[0]] = +parts[1];
}
else {
// No
obj[parts[0]] = parts[1];
}
});
That assumes . as the decimal separator, and assumes there won't be a thousands separator.
Side note: Above I've used Array#forEach, which is an ES5 feature not present on older browsers. forEach can be "shimmed" on older browsers, though. You can see all sorts of ways of looping through arrays in this answer here on SO.