I've got json data.
[
["Fruit","Lychee Magic","Dusk"],
["Veggies","Long Beans","Rampage"],
["Fruit","Mango Aroma Sweet","Dawn"]
]
I've got buttons. The first part of the button text is similar to a json data.
<button type="button" class="mood">Mango</button>
<button type="button" class="mood">Lychee</button>
How can I match the button text to the json data and get the full line in to an array?
var butTxArr = [];
$("#intoArr").click(function(){
$('.mood').each(function(){
var obj = //how to match?
butTxArr.push(obj);
})
});
excepted output:
butTxArr = ["Fruit","Lychee Magic","Dusk", "Fruit","Mango Aroma Sweet","Dawn"];
Something like this?
$("#intoArr").click(function () {
var butTxArr = [];
$('.mood').each(function () {
// trim button text
var text = $(this).text().replace(/^\s*/g, '').replace(/\s*$/g, '');
data.forEach(function (row) {
// see if the row contains the text
if (row.toString().indexOf(text) !== -1)
// append to array
butTxArr = butTxArr.concat(row);
})
})
// we're done!
console.log(butTxArr)
});
$(document).ready(function() {
var data = [
["Fruit", "Lychee Magic", "Dusk"],
["Veggies", "Long Beans", "Rampage"],
["Fruit", "Mango Aroma Sweet", "Dawn"]
];
$("#intoArr").click(function() {
var butTxArr = [];
$('.mood').each(function() {
// trim button text
var text = $(this).text().replace(/^\s*/g, '').replace(/\s*$/g, '');
data.forEach(function(row) {
// see if the row contains the text
if (row.toString().indexOf(text) !== -1)
// append to array
butTxArr = butTxArr.concat(row);
})
})
// we're done!
alert(butTxArr)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" class="mood">Mango</button>
<button type="button" class="mood">Lychee</button>
<button id="intoArr">Show</button>
I would approach it something like this:
var butTxArr = [];
// create a temporary array
var temp = [];
$("#intoArr").click(function () {
$('.mood').each(function () {
// grab the text from the mood class
var txt = $(this).text();
// loop over the data array
for (var i = 0, l = arr.length; i < l; i++) {
// use `some` to check to see if the text appears
// in any of the element, and if it does, add it
// to the temporary array
var found = arr[i].some(function (el) { return el.indexOf(txt) > -1; });
if (found) temp.push(arr[i]);
}
});
// flatten the temporary array
butTxArr = [].concat.apply([], temp);
});
DEMO
You could do something like this:
$("#intoArr").click(function(){
$('.mood').each(function(){
for (var i=0;i<array.length;i++) {
if(array[i].toString().indexOf($(this).text()) > -1) {
butTxArr.push(array[i]);
}
}
})
for (var a=0;a<butTxArr.length;a++) {
alert(butTxArr[a]);
}
});
Demo here.
You can use high order function with the .filter() method, by using the functional way. So you can create a function generator, and make your code more reusable and more cleaner.
//Create a function generator to filter our array
function filterBy(filter){
return function(elm){
return elm.join('').indexOf(filter) > -1;
}
}
var filtered = [];
$('#intoArr').click(function(){
$('.mood').each(function(){
//Retrieve text param
var txt = $(this).text();
//Filter our array by using high order function and filter method
//and push it into our filtered array
filtered.push(array.filter(filterBy(txt))[0]);
});
//Flat the result
filtered = [].concat.apply([], filtered);
console.log(filtered)
});
Related
say if I have csv file with :
Heading 1 , Heading 2 , Heading 3
Value 1 , Value2 , Value 3
All I want is to create a map that stores Heading 1 as a key and Heading 2 as value;
like map.set(value1 , value2)
How do I do this while I read the file in javascript ?
function processData(allText) {
var allTextLines = allText.split("\r");
for (var i=1; i<allTextLines.length; i++) {
var data = allTextLines[i].split(',');
console.log(data[0]);
map1.set(data[0] , data[1]);
}
}
so far I tried to do this . But it doesn't work. It doesn't read the file at all. Any help is appreciated.
Thanks
If you have a series of items separated by commas (,), the you can iterate the String and explode or split the items. This can be done with Vanilla JavaScript. The magic part is the for() loop; iterating it by 2 instead of by 1, which is most commonly seen.
$(function() {
var myString = "Header 1,Value 1,Header 2,Value 2,Header 3,Value 3";
var parts = myString.split(",");
var myData = {};
for (var i = 0; i < parts.length; i += 2) {
myData[parts[i]] = parts[i + 1];
}
console.log(myData);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
If your file has multiple lines, and the first line is Headers, for example:
Header 1,Header 2,Header 3
Value 1,Value 2,Value 3
Value 4,Value 5,Value 6
You'll have to treat it differently. When it's brought into JS, it will be one big String, and you will have to first split it by End Of Line (EOL). This will create an Array of Strings that must be iterated. You will want to make an Array of Keys and then a Matrix of Values.
Since the file is Local, you will need to first get the File from the User. This is discussed here: How to read data From *.CSV file using javascript? and here: Reading in a local csv file in javascript? You will have to determine the best method for yourself.
One way is to use a File Input. There are drawbacks and caveats due to security and browsers, but it might work.
$(function() {
var fileInput = $("#getFile");
function toObj(keys, vals) {
var obj = {};
for (var i = 0; i < keys.length; i++) {
obj[keys[i]] = vals[i];
}
return obj;
}
function stringToObject(str, header) {
if (header == undefined) {
header = false;
}
var lines = str.split("\n");
var k = [],
m = [];
if (header) {
k = lines.splice(0, 1);
k = k[0].split(",");
}
$.each(lines, function(i, el) {
if (el.length) {
m.push(el.split(","));
}
});
if (k.length) {
var r = [];
$.each(m, function(i, el) {
r.push(toObj(k, el));
});
return r;
} else {
return m;
}
}
function readFile() {
var reader = new FileReader();
reader.onload = function() {
var newData = stringToObject(reader.result, $("#header").prop("checked"));
console.log(newData);
$("#out").html("<pre>" + reader.result + "</pre>");
};
reader.readAsBinaryString(fileInput[0].files[0]);
};
fileInput.change(readFile);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="file input">
<input type="checkbox" id="header" checked="checked"> <label>CSV Header</label><br />
<input type="file" id="getFile" />
</div>
<div id="out"></div>
I've got the following parameters
/Search?category=1&attributes=169&attributes=172&attributes=174&search=all
I'm trying to get just the attributes querystring values as an array in javascript, for example.
attributes = ['169','172','174']
Bearing in mind there may be other parameters that are irrelevant such as search or category.
Might not the proper answer but just tried
var str = "/Search?category=1&attributes=169&attributes=172&attributes=174&search=all";
var str1 = str.split("&");
var attributesArray = [];
for(var i=0; i<str1.length; i++) {
if (str1[i].includes("attributes")) {
attributesArray.push(str1[i].replace("attributes=", ""));
}
}
Fiddle https://jsfiddle.net/5Lkk0gnz/
You can do it like this:
(function() {
function getJsonFromUrl(url) {
var query = url.substr(1);
var arr = [];
query.split("&").forEach(function(part) {
var item = part.split("=");
arr.push(decodeURIComponent(item[1]));
});
return arr;
}
var url = "https://example.com?category=1&attributes=169&attributes=172&attributes=174&search=all";
var params = getJsonFromUrl(url);
console.log(params);
})();
Hope this helps!
This should do what you want, assuming you already have your url:
var url = "/Search?ategory=1&attributes=169&attributes=172&attributes=174&search=all";
var attrs = url
.match(/attributes=\d*/g)
.map(function(attr){
return Number(attr.replace("attributes=", ""));
});
console.log(attrs); //=> [169, 172, 174]
In Javascript, I have a string of options for a select tag. This is my string:
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>';
In Javascript, I want to convert it to a 2-dimensional Array where 1st dimension will store the id and 2nd dimension will store the text of an option.
How can I do that? I am looking for Javascript solution; I am open to 3rd party solutions also like jQuery.
You can do it by converting the string into DOM options, then iterating over them, so:
var s = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option>'
function optionsAsArray(s) {
var sel = document.createElement('select');
var result = [[],[]];
sel.innerHTML = s;
Array.prototype.forEach.call(sel.options, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
console.log(JSON.stringify(optionsAsArray(s))); // [["","1","2"],["","Self Service","Administrator"]]
You can also do it by parsing the string, but that may be more work.
Edit
You can also use the new DOMParser, but fairly recent browsers are required for support:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
var result = [[],[]];
Array.prototype.forEach.call(opts, function(opt) {
result[0].push(opt.id);
result[1].push(opt.text);
});
return result;
}
The above creates an array of:
[[id0, id1, id2, ...], [text0, text1, text2, ...]]
if you want pairs like:
[[id0, text0], [id1, text1], ...]
Then the above can be:
function optionsAsArray(s) {
var parser = new DOMParser();
var opts = parser.parseFromString(s, "text/html").querySelectorAll('option');
return Array.prototype.map.call(opts, function(opt) {
return [opt.id, opt.text];
});
}
// [["",""],["1","Self Service"],["2","Administrator"]]
which can be reduced to:
function optionsAsArray(s) {
return Array.prototype.map.call(new DOMParser().parseFromString(s, "text/html").querySelectorAll('option'), function(opt) {
return [opt.id, opt.text];
});
}
I have used jQuery for the solutions below.
If you want the array to be made from DOM then you can do this
<select id="selectopt"><option id="">Select</option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option></select>
var arr = [];
console.log('====array 1===');
$('select option').each(function(){
var id = $(this).attr('id');
var value = $(this).text();
arr.push([id, value]);
console.log(arr);
});
If you need it to be made using the string then use $.parseHTML for converting the string to DOM nodes.
var arr2 = [];
var myOptionsString = '<option id=""></option><option id="1">Self Service</option><option id="2">Administrator</option><option id="3">Guest</option><option id="4">Limited</option>';
var options = $.parseHTML(myOptionsString);
console.log('====array 2===');
for (var i=0; i< options.length; i++){
var id1 = options[i].id;
var value1 = options[i].value;
arr2.push([id1, value1]);
console.log(arr2);
}
Fiddle Demo
Javascript (using jQuery):
var paragraphs = [
['This is my first paragraph content of the first array', 'This is my second paragraph content of the first array', 'This is my third paragraph content of the first array'],
['This is my first paragraph content of the second array', 'This is my second paragraph content of the second array', 'This is my third paragraph content of the second array']
],
text_box_value,
unused_paragraphs = null;
$(document).ready(function(){
$('input#text_box').keyup(function(){
text_box_value = $(this).val();
});
$('input#submit_button').click(function(){
if(unused_paragraphs === null) {
unused_paragraphs = paragraphs;
}
for(var i = 0; i < unused_paragraphs.length; i++) {
if(unused_paragraphs[i].length == 0)
unused_paragraphs[i] = paragraphs[i];
while(unused_paragraphs[i].length != 0) {
var rand = Math.floor(Math.random() * unused_paragraphs[i].length);
if(unused_paragraphs[i][rand].search(text_box_value) !== -1) {
$("#paragraphs_container").append('<p>' + unused_paragraphs[i][rand] + '</p>');
break;
}
unused_paragraphs[i].splice(rand, 1);
}
}
console.log(unused_paragraphs);
console.log(paragraphs);
});
});
My question is why when I use splice method on unused_paragraphs variable it also remove the value from the paragraphs variable
Later edit JSFiddle
javascript objects/array are stored by reference.
If you want a copy that's a trick:
if(typeof unused_paragraphs == "undefined") {
var unused_paragraphs = [];
for(var i = 0; i<paragraphs.length; i++) {
unused_paragraphs[i] = paragraphs[i].slice(0);
}
}
and
unused_paragraphs[i] = paragraphs[i].slice(0);
to copy the obect to new object..
try this..
var unused_paragraphs= jQuery.extend(true, {}, paragraphs);
here is just an example of copied objects.. check it out
http://jsfiddle.net/5ExKF/3/
I have a text array. I want to display the first entry on page load. And then replace the text with the next entry when I click a button. If I keep clicking the button I want the text to continuously be replaced by waht is next in the array, and when it gets to the end start back at the first entry. Can someone please show me an example code for that. I am new to this.
Here's what I have
$(document).ready(function(){
var arr = new Array("One","Two","Three");
var len=arr.length;
$('#next').click(function(){
for(var i=0; i<len; i++) {
$('#quote').html(arr[i]);
}
});
});
Something like the following should do the trick:
<script type="text/javascript">
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var count = -1;
return function() {
return wordArray[++count % wordArray.length];
}
}());
</script>
<p id="foo"> </p>
<button onclick="
document.getElementById('foo').innerHTML = nextWord();
">Update</button>
Edit
Radomised version:
var nextWord = (function() {
var wordArray = ['fe','fi','fo','fum'];
var copy;
return function() {
if (!copy || !copy.length) copy = wordArray.slice();
return copy.splice(Math.random() * copy.length | 0, 1);
}
}());
The following should do it http://jsfiddle.net/mendesjuan/9jERn/1
$(document).ready(function(){
var arr = ["One","Two","Three"];
var index = 0;
$('#next').click(function(){
$('#quote').html(arr[index]);
index = (index + 1) % arr.length ;
});
});
Your code was writing all three values each time you clicked it (but only displaying that last value)
I think something like this would work
The javascript would look like:
// assuming maxTextArrayIndex & textArray are defined & populated
var textDisplayIndex = -1;
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
function nextElement()
{
textDisplayIndex += 1;
if (textDisplayIndex > maxTextArrayIndex)
{
textDisplayIndex = 0;
}
document.getElementById('textDisplay').innerHTML = textArray[textDisplayIndex];
}
The html would look like:
<body onLoad=nextElement()>
...
<elementToDisplayText id=textDisplay></elementToDisplayText>
<button onClick=nextElement()>Next</button>