I want to convert this array into string includes space elements in javascript. space doesn't show after return.
let results = ['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X'];
const result = () =>
{
for(let i = 0; i<results.length; i++)
{
return results;
}
}
result();
// Expected Output : "Hello EveryOne My Name is X";
use Array.prototype.join with empty string as separator:
const result = () => {
let results = ['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X'];
return results.join('')
}
console.log(result())
You need to concatenate the elements in the for-loop:
const result = (results=[]) => {
let str = '';
for(let i = 0; i < results.length; i++) {
str += results[i];
}
return str;
}
console.log( result(['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X']) );
Another way using .join:
const result = (results=[]) => {
return results.join('');
}
console.log( result(['Hello',' ',' ',' ','EveryOne',' ',' ',' ','My',' ','Name',' ','is',' ','X']) );
Since reactjs tag is there, am assuming issue rendering. Use HTML entity for ' ', that should display correct as in snippet.
const Component = () => {
let results = [
"Hello",
" ",
" ",
" ",
"EveryOne",
" ",
" ",
" ",
"My",
" ",
"Name",
" ",
"is",
" ",
"X",
];
return (
<div>
{" "}
{results.map((word) => (
word === ' ' ? <span> </span> : <span> { word } </span>
))}{" "}
</div>
);
};
ReactDOM.render(<Component />, document.getElementById("app"));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>
<div id="app"> </div>
You can convert your array to string, and then split commas per something like: results.toString().split(',').join('');
let result = arr.filter(item => {
if (item !== " "){
return item
};
});
console.log("result",result)
Related
How can I change a counter variable from a number to a letter? Say I have five sections that each read "Section A", "Section B", so on... And I want to change their href attributes as they are being mapped out from "section1" to "sectionA", "section2" to "sectionB", etc?
var sectionNumberLink = 0;
var sectionLetters = assessmentSections.map(function (section) {
sectionNumberLink++;
return '<div class="assess-sec-link">' + '<a href="section' +
sectionNumberLink + '">' + "Section" + '</a>' + '</div>';
}).join('');
You can use String.fromCharCode() and String.prototype.charCodeAt() to convert the number to a letter
Example:
Warning: This will fail if you have more than 26 sections
function toLetter(number) {
let base = 'A'.charCodeAt(0);
return String.fromCharCode(base - 1 + number);
}
console.log(toLetter(1)); // A
console.log(toLetter(2)); // B
If you need more than 26 sections, a bit more code is required:
function toLetter(num) {
let a = "A".charCodeAt(0);
let result = '';
for (let base = 1, mod = 26; (num -= base) >= 0;base = mod, mod *= 26) {
result = String.fromCharCode(num % mod / base + a) + result;
}
return result;
}
console.log(toLetter(1)); // A
console.log(toLetter(27)); // AA
In your code snippet you could use it like this:
let sectionLetters = assessmentSections.map((section, idx) => {
return `
<div class="assess-sec-link">
Section
</div>`;
}).join('');
You can use index to calculate the alphabet in the .map() method,
//sample
var assessmentSections = ["section1", "section2", "section3"]
var sectionLetters = assessmentSections.map(function (section, index) {
return '<div class="assess-sec-link">' + '<a href="section' +
String.fromCharCode('A'.charCodeAt(0) - 1 + (index+1)) + '">' + "Section" + '</a>' + '</div>';
}).join('');
console.log(sectionLetters)
You could do something like:
const alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
//As #georg suggested, you could do it like:
for(let c=1;c<=alphabet.length;c++){
console.log("Section "+alphabet[c-1])
}
So, you can call alphabet[number-1] to change NUMBER to CHARACTER.
Remember arrays indexes start from 0, that's why it needs to be number-1.
I would try to structure my HTML so I can use an <ol type="A"> instead of <div>s, so that I get automatic ordering with uppercase letters automatically, without me having to do index-to-letter calculations:
// create dummy data
var assessmentSections = Array.from({ length: 50 }, ( item, i ) => {
return { url: i + 1 };
});
var sections = assessmentSections.map(( section, i ) => {
return `<li class="assess-sec-link">Section ${ i + 1 }</li>`;
});
document.querySelector( 'ol' ).innerHTML = sections.join( '' );
<ol type="A"></ol>
I have an array of files in Javascript. How can I create a string with their names and sizes?
Example:
[ {File1} {File2} ] => "File: my_file1 size: size1 bytes, "File: my_file2 size: size2 bytes".
Not using for - I want to use functions :)
If use for it could be something like this
function createStringForFileArray(arr){
let result = "";
for (let i = 0; i <arr.length; i++ ){
result+= "File"+arr[i].name+" size "+arr[i].size+" ";
}
return result;
}
Iterate using Array#map and create a string for each file, then join all the strings:
const files = [{ name: 'file1', size: 1111 }, { name: 'file2', size: 2222 }];
const result = files.map(({ name, size }) => `File: ${name} size: ${size} bytes`).join(', ');
console.log(result);
You can simply use Array.prototype.reduce() to return a unique string from all your array elements.
Your code would be like this:
function createStringForFileArray(arr) {
return arr.reduce(function(a, b, i){
return a + "File: " + b.name + " size: " + b.size + (i !== array.length - 1 ? ", " : "");
}, "");
}
Demo:
This is a working Demo:
var array = [{
name: "file1",
size: "500Mb"
},
{
name: "Test",
size: "0Kb"
}, {
name: "TAnother File",
size: "30Kb"
}
];
function createStringForFileArray(arr) {
return arr.reduce(function(a, b, i){
return a + "File: " + b.name + " size: " + b.size + (i !== array.length - 1 ? ", " : "");
}, "");
}
console.log(createStringForFileArray(array));
Or you can use .map() function like this:
function createStringForFileArray(arr) {
return array.map(function(f) {
return "File: " + f.name + " size:" + f.size;
}).join(", ");
}
You could try map with reduce:
let str = files
.map(f => "File: " + f.name + " size: " + f.size)
.reduce((prev, curr) => prev + ", " + curr);
Edit: You can do it with just reduce. The original solution by #chsdk did this and was posted before mine, but it had an error (now corrected). So you may want to accept that answer instead.
let str = files.reduce((prev, curr, index, arr) => {
return prev + "File: " + curr.name + " size: " + curr.size + (index === arr.length - 1 ? "" : ", ");
}, "");
Having the reference to a specific DOM element (e.g. <mark>), how can we get the full word containing that element?
For example :
H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!
I expect to get the following output :
First <mark>: Hello
Second: World
Third: Hello
Fourth: Pluto
var $marks = $("mark");
var tests = [
"Hello",
"World",
"Hello",
"Pluto",
];
function getFullWord($elm) {
// TODO: How can I do this?
// This is obviously wrong.
return $elm.html();
}
var $marks = $("mark");
tests.forEach(function(c, i) {
var word = getFullWord($marks.eq(i));
if (word !== c) {
alert("Wrong result for index " + i + ". Expected: '" + c + "' but got '" + word + "'");
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
H<mark>ell</mark>o Wor<mark>l</mark>d, and He<mark>llo</mark>, <mark>Pluto</mark>!
If you need fast and compact code (one-liner), try this:
var $marks = $('mark');
$marks.each(function() {
var wholeWord = (this.previousSibling.nodeValue.split(' ').pop() +
this.textContent +
this.nextSibling.nodeValue.split(' ')[0]
).replace(/[^\w\s]/gi, '');
});
JSFiddle (with logging into console and comments)
I have a very simple snipplet for a json array and a javascript function that now returns a single argument:
<!DOCTYPE html>
<html>
<body>
<h2>JSON Array Test</h2>
<p id="outputid"></p>
<script>
var arrayinput = '{"collection":[' +
'{"firstAttr":"XXXA","secAttr":"13156161","lastAttr":"01" },' +
'{"firstAttr":"XXXB","secAttr":"11153325","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"14431513","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"161714","lastAttr":"01" },' +
'{"firstAttr":"XXXC","secAttr":"151415","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"114516","lastAttr":"02" },' +
'{"firstAttr":"XXXC","secAttr":"131417","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"1311865","lastAttr":"03" },' +
'{"firstAttr":"XXXC","secAttr":"1314153","lastAttr":"01" },' +
'{"firstAttr":"XXXC","secAttr":"13312163","lastAttr":"01" }]}';
obj = JSON.parse(arrayinput);
document.getElementById("outputid").innerHTML =
obj.collection[1].firstAttr + " " + obj.collection[1].secAttr;
</script>
</body>
</html>
Now the problem is that I don't want to return just one value but multiple ones. For example all entrys with lastAttr=01 should be returned.
Therefore I would need something along the line of:
for(var i in obj) {
if(lastAttr[i]="01") {
document.getElementById("outputid").innerHTML =
obj.collection[i].firstAttr + " " + obj.collection[i].secAttr;
} else {
}
}
Any idea on how to make this work?
If you want to perform a where you need to use Array.prototype.filter:
var filteredArr = arr.collection.filter(function(item) {
return item.lastAttr == "01";
});
And, finally, you can use Array.prototype.forEach to iterate results and perform some action:
var outputElement = document.getElementById("outputid");
filteredArr.forEach(function(item) {
// Check that I used insertAdyacentHtml to be sure that all items
// will be in the UI!
outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
Also, you can do it fluently:
var arr = {
collection: [{
firstAttr: "hello",
secAttr: "world",
lastAttr: "01"
}, {
firstAttr: "hello 2",
secAttr: "world 2",
lastAttr: "01"
}]
};
var outputElement = document.getElementById("outputid");
var filteredArr = arr.collection.filter(function(item) {
return item.lastAttr == "01";
}).forEach(function(item) {
outputElement.insertAdjacentHTML("afterbegin", item.firstAttr + " " + item.secAttr);
});
<div id="outputid"></div>
You need to iterate over the collection Array and append the new stuff. Right now you're iterating the outer object and overwriting the .innerHTML each time.
var out = document.getElementById("outputid");
for (var i = 0; i < obj.collection.length; i++) {
if(obj.collection[i].lastAttr=="01") {
out.insertAdjacentHTML("beforeend", obj.collection[i].firstAttr + " " + obj.collection[i].secAttr);
}
}
Note that I used == instead of = for the comparison, and .insertAdjacentHTML instead of .innerHTML.
if you want to replace html try this
(someCollection) array;
var r = new Array();
var j = -1;
r[++j] = '<ul class="list-group">';
for (var i in array) {
var d = array[i];
if (d.attribute== somevalue) {
r[++j] = '<li class="list-group-item">'
r[++j]=d.otherattribute;
r[++j] = '</li>';
}
}
r[++j] = '</ul>';
//for(var b in r) //alert to see the entire html code
//{ alert(r[b]);}
firstLoadOnPage = false;
var list = document.getElementById('SymptomSection');
list.innerHTML = r.join('');
this replaces the inside of element with classname "SymptomSection"
Again some Problems.
I' get some values of a Textfield ,shown like them:
134.45 987.46 -89.10
224.67 127.26 -19.12
764.32 187.96 -78.25
...and so on...
I'm get them with
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text();
}
i need them in
1;134.45;987.46;-89.10< br /><<< yes also the break - it will written in a .TXT file >>>
2;224.67;127.26;-19.12< br />
3;764.32;187.96;-78.25< br />
...and so on...
I couldn't figure it out how to. seems insoluble :(
The hekp from "guest271314" was perfekt. i've built it a Little more dynamic.
function LineWriteToNp01() {
var getNP01TableData = $('#null_tabelle_dues1_text').text().replace(/\s+X/, "");
var arr = getNP01TableData.split(/\s+/);
var _arr = [];
var index = 1;
for (var i = 1; i <= (arr.length-1)/3; i++) {
_arr.push( i + ";" + arr[index] + ";" + arr[index + 1] + ";" + arr[index + 2] + "<br />\n");
index = index + 3;
}
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
// ... code to write it back in txt file
}
Thanks a lot # all for your Help
Well, let's look at what you've got: you have a text block, with numbers separated by spaces. That's something we can work with.
The .split(" ") function will separate the numbers and put them in an array; you could do a
getNP01TableData.split(" ") and your result will be:
[" ", "134.45 ", "987.46 ", "-89.10", "
", "224.67 ", "127.26 ", "-19.12
", "764.32 ", "187.96 ", "-78.25" ]
And that definitely looks like something you can work with. Throw that bad boy into a loop:
var text = "";
for (var i = 0; i<arr.length/3; i++) {
text = text + i;
for (j = 0; j<3; j++) {
text=text+";"+arr[3*i + j]
}
text = text+"</br";
}
That might need a little fiddling, but you get the idea. Also, the .trim() function is useful for removing unwanted whitespace.
Try
var text = "134.45 987.46 -89.10 224.67 127.26 -19.12 764.32 187.96 -78.25";
var arr = $.map(text.split(" "), function (value, index) {
return value === "" ? null : [value]
});
var _arr = [];
_arr.push("1;" + arr.slice(0, 3).join(",").replace(/,/g, ";") + "<br />");
_arr.push("2;" + arr.slice(3, 6).join(",").replace(/,/g, ";") + "<br />");
_arr.push("3;" + arr.slice(6, 9).join(",").replace(/,/g, ";") + "<br />");
_arr = _arr.toString().replace(/,/g, "");
var file = new Blob([_arr], {
"type": "text/plain"
});
var reader = new FileReader();
reader.addEventListener("loadend", function (e) {
console.log(e.target.result);
});
reader.readAsText(file);
jsfiddle http://jsfiddle.net/guest271314/YpBxA/