Do I have to use .each() for this? - javascript

I want to look up all the items with a certain selector and return all of their titles as quickly as possible. I know I can use .each() to loop through them and populate a variable, but I would like to use .join() if possible.
Here is how I would do it using .each()
var pop = "";
$("a").each(function(i,v){
var pop = pop + $(this).attr("title") + ',';
});
//now pop looks like: "title1,title2,etc"
How could I return all the titles in a CSV format using .join() ?
I tried this but it didn't work:
var pop = $("a").title.join(',');

You have to iterate the array, yes. But you can use map for this specific case:
var arr = $("a").map(function () { return $(this).attr('title') }).get();
var csv = arr.join(',');

Related

Using map\reduce with nested elements in javascript

I have a search form that allows the user to add as many search terms as they like. When the user enters all of the search terms and their search values and clicks search, a text box will be updated with the search terms. I've got this working with a for loop, but I'm trying to improve my dev skills and am looking for a way to do this with map\filter instead.
Here's the code I'm trying to replace:
var searchTerms = $("#search-form").find(".mdc-layout-grid__inner");
var searchString = "";
for(var i = 0; i < searchTerms.length - 1; i ++)
{
var select = $(searchTerms[i]).find(".select2-selection")[0];
var selectText = $(select).select2('data')[0].text + ":";
var textBox = $(searchTerms[i]).find(".mdc-text-field__input")[0];
searchString = searchString += selectText.replace(/\./g,"").replace(/ /g,"") + textBox.value;
if(i < searchTerms.length - 1)
{
searchString = searchString += " ";
}
}
$("#er-search-input").val(searchString);
Here's a codepen of the current solution.
i'm trying the below, but I get the feeling I'm miles away:
const ret = searchTerms.map((u,i) => [
$($(u[i]).find(".select2-selection")[0]).select2('data')[0].text + ":",
$(u[i]).find(".mdc-text-field__input")[0].value,
]);
My question is, is it possible to do this with map?
Firstly you're repeatedly creating a jQuery object, accessing it by index to get an Element object only to then create another jQuery object from that. Instead of doing this, you can use eq() to get a specific element in a jQuery object by its index.
However if you use map() to loop through the jQuery object then you can avoid that entirely by using this to reference the current element in the iteration. From there you can access the required elements. The use of map() also builds the array for you, so all you need to do is join() the results together to build the required string output.
Finally, note that you can combine the regex expressions in the replace() call by using the | operator, and also \s is more robust than using a whitespace character. Try this:
var $searchTerms = $("#search-form").find(".mdc-layout-grid__inner");
var searchString = $searchTerms.map(function() {
var $searchTerm = $(this);
var selectText = $searchTerm.find('.select2-selection').select2('data')[0].text + ':';
var $textBox = $searchTerm.find('.mdc-text-field__input:first');
return selectText.replace(/\.|\s/g, "") + $textBox.val();
}).get().join(' ');
$("#er-search-input").val(searchString);

Replace different Values in String?

I have a string which looks like this: (id:561644cdb40fbe0100247dd7:q) (id:56165d8a79c8c40100adbdb6:q) and I need to replace the different id's with different values. I already have the id's in a variable and trying to loop through with something like this var mailId = "(id:" + rplcId + ":q)"; But If I use the replace() function it doesnt work...Any other suggestions?
You can select the id with:
"(id:56165d8a79c8c40100adbdb6:q)".split(":")[1]
var id = "(id:561644cdb40fbe0100247dd7:q)";
var idArr = id.split(":");
idArr[1] = newId; //56165d8a79c8c40100adbdb6
var mailId = idArr[0]+idArr[1]+idArr[2];
and please provide your full code

Save and print list with array

I need help print and save element in an array in javascript. I know that I have to create an array, and then use a for-loop to save and print it, but i don't know how. What i want to do i so make a simple currency converter, use a for-loop with an array to save the converted input and display it. Here is my code:
JAVASCRIPT
var input = document.querySelector("#input");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(("Dollar:" + input.value*dollar) + ("Euro:" + input.value*euro));
}
};
HTML
<p>
<form>
<label>Kronor: <input type="text" id="kronor"/></label>
<br><input type="submit" id="convert" value="Omvandla"/>
</from>
</p>
How can I append the converted value after the submit button?
If you want to display one Conversion Result after another, you could do this like this:
var input = document.querySelector("#kronor");
var convert = document.querySelector("#convert");
var dollar = 0.51;
var euro = 0.11;
var conversionArray = [];
convert.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
var dollarResult = input.value*dollar;
var euroResult = input.value*euro;
var newArrayEl = {
dollar: dollarResult,
euro: euroResult
};
conversionArray.push(newArrayEl);
console.log(conversionArray);
document.getElementById("convertedValue").innerHTML = "Dollar: " + dollarResult + " Euro: " + euroResult + "<br>" + document.getElementById("convertedValue").innerHTML;
}
};
Then you can access single values of the conversion by e.g. conversionArray[indexOfElement].dollar
This way you don't need an array to store the values. If you really need thos wvalues again, let me know, and im showing you how to store the array.
Here is a Fiddle, that shows how it works.
In javascript the way you add elements to an array is the push function
var myArray = [];
myArray.push(15);
Then to loop through the elements you can do something like this
for(var elem in myArray){
//Do something with elem
}
From your problem description it is hard to figure out what you are trying to do with your code. Hopefully this will help with array manipulation
You can add an element to the end of an array by using the array.push() function. I your example you would do something like:
array = [];
...
omvandla.onclick = function (){
if(isNaN(input.value)){
alert ("Use numbers");
}
else{
console.log(...);
array.push(input.value);
}
};
For more information about JavaScript arrays see here.

how to loop though div and get each value

I am trying to figure out how to get each value within my div. I am using
var cart = $('.basic-cart-cart-node-title.cell').text();
It is giving the results of OI-01OP-01OS-10-5SOR-04OR-05
I need to view them one by one: OI-01, OP-01, OS-10-5S, OR-04 OR-05.
So that I can match them against another field.
If you care to help me further, I have another div on the page:
var ParNum = $('.assess-title').text();
I would like to compare the values returned from the var cart and see if that value is in the ParNum. If it is there, I would like to apply a class.
Any help would be greatly appreciated.
Thanks!
You can store the values in an array using .map() method:
var values = $('.basic-cart-cart-node-title.cell').map(function() {
return $.trim( $(this).text() );
}).get();
For checking existence of the ParNum value in the array:
var does_exist = values.indexOf(ParNum) > -1;
Try this to iterate over elements:
var text = '';
$('.basic-cart-cart-node-title.cell').each(function (i, div) {
text += ' ' + $(div).text();
});
or this to get an array of matching div elements:
var divs = $('.basic-cart-cart-node-title.cell').toArray();
for (var i = 0; i < divs.length; i++) {
// $(div).text();
}
Reason for this is that $('.basic-cart-cart-node-title.cell') returns all div's at once, and you need to loop through the result. More specifically, $(selector) returns a so-called "wrapped set". It can be used to access each matching element (as I've shown above) or it can be used to apply any other jQuery function to the whole set at once. More info here.
var text = "";
$('.basic-cart-cart-node-title.cell').each(function(){
text += $(this).text() + ", ";
});
// remove the last ", " from string
text = text.substr(0, text.length -2);
var cart = [];
$('.basic-cart-cart-node-title.cell').each(function {
cart.push($(this).text());
}
This performs the matching and class adding you mentioned in the question.
var ParNum = $('.assess-title').text();
$('basic-cart-cart-node-title.cell').each(function () {
if ($(this).text() == ParNum) {
$(this).addClass("someclass");
}
}
You should try using
var cart ='';
$('.basic-cart-cart-node-title'.find('.cell').each(function()
{
cart = cart + $(this).val();
});
Hope it works for you.
var cart = $('.basic-cart-cart-node-title.cell').text().match(/.{5}/g);
This will give you an array with items 5 chars long. Regexes arent very fast, but a loop might be slower
Or easier to read, and in a string with commas:
var cart = $('.basic-cart-cart-node-title.cell').text(); // get text
cart = cart.match(/.{1,5}/g); // split into 5 char long pieces
cart = cart.join(",",); join on comma

Populate a javascript array with links of a specific class

I'm looking to take a website source and populate an array with a collection of links, filtered by their a class.
Say, for instance, the links were <a class="title">, how could I target each class and add the URL to an array?
Would Javascript or jQuery work better?
var arr = new Array();
$("a.title").each(function()
{
arr.push($(this).attr("href"));
});
So, basically you create an array by using the Array constructor. Then you use JQuery's each method to iterate over the links with class title, getting their urls using the attr method and pushing them in the array along the way.
It's pretty easy with jQuery:
var arr = [];
var ptr = 0;
$('.title').each(function() {
arr[ptr] = $(this).attr('href');
ptr++;
})
Something like
var collectionOfLinks = {};
$('a').each(function() {
var cl = $(this).attr('class');
if (collectionOfLinks[cl] === undefined) {
collectionOfLinks[cl] = [];
collectionOfLinks[cl].push($(this).attr('href'));
}else{
collectionOfLinks[cl].push($(this).attr('href'));
}
});
With this you end up with an object whose properties names are the classes of the <a> elements and whose values are arrays of href
With jQuery, you can do var urls = $("a.title").attr("href")to get what you want.
You can do something like below,
var linkURL = [];
$('a.title').each (function () {
linkURL.push(this.href);
});

Categories

Resources