Printing particular element of set container in javascript - javascript

I am new to javascript. I want to fetch a particular element from set container.
Here is my source code:
var i, item, val = '';
var setObj1 = new Set();
for (i = 0; i < 5; i++) {
setObj1.add(i);
}
for (item of setObj1.values()) {
val += item + ' ';
}
document.getElementById('demo').textContent = "The set values are: " + val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + setObj1.values[1];
<div id="demo"> </div>
<div id="demo1"> </div>
Please correct my syntax or suggest me a approach to print particular index value of set.

You can do it like this
var i, item,val = '';
var setObj1 = new Set();
for(i=0;i<5;i++){
setObj1.add(i);
}
for (item of setObj1.values()){
val+=item + ' ';
}
var iterator = setObj1.values();
iterator.next();
document.getElementById('demo').textContent = "The set values are: "+val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: "+ iterator.next().value;
Note: If you want to get values with their index it would be better to use arrays instead of Set

Although you can do that, it's expensive. Sets aren't for index-oriented or key-oriented operations (use an array or Map for that).
The expensive way is to converting the set to an array (which uses values indirectly through the set's iterator and iterates all the way to the end to get the full set) and index into the array:
document.getElementById('demo1').innerHTML = [...setObj1][1];
Live Example:
var i, item, val = '';
var setObj1 = new Set();
for (i = 0; i < 5; i++) {
setObj1.add(i);
}
for (item of setObj1.values()) {
val += item + ' ';
}
document.getElementById('demo').textContent = "The set values are: " + val;
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + [...setObj1][1];
<div id="demo"> </div>
<div id="demo1"> </div>
But here's your example using an array instead:
var i, item, val = '';
var values = [];
for (i = 0; i < 5; i++) {
values[i] = i;
}
document.getElementById('demo').textContent = "The set values are: " + values.join(" ");
document.getElementById('demo1').innerHTML = "The set value at index 2 is: " + values[1];
<div id="demo"> </div>
<div id="demo1"> </div>

Related

Sum values from an Array, JavaScript

Prompting the user for many inputs, storing it in an array, then printing summation , average, largest number, smallest number and bigger number than mean number.
I have defined a JavaScript variables called magicnumber which is a new Array , and print the value of array, like this:
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = parseInt(magicnumber.push(prompt("Enter data value number " + i)));
var s = magicnumber.join(', ');
}
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + s + "<br>";
}
<div id="demo1"></div>
how I can summation it?
You can use Array#reduce() to get the sum
var magicnumber = [];
mymagicNumber();
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
var promptValue = prompt("Enter data value number " + i);
magicnumber.push(+promptValue);
}
var sum = magicnumber.reduce((a,b)=>{return a+b},0);
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + magicnumber.join(', ');
document.getElementById("sum").innerHTML = "The sum : " + sum;
}
<div id="demo1"></div>
<div id="sum"></div>
Here are 2 more ways to find the summation, without using for loop.
var magicnumber = [];
function mymagicNumber() {
//Specify the size of array
var size = parseInt(prompt("How many data values do you need have?"));
for (var i = 1; i <= size; i++) {
//sorted in array
var num = magicnumber.push(parseInt(prompt("Enter data value number " + i)));
}
var data = magicnumber.join(', ');
var s1 = magicnumber.reduce(function(acc, val) {
return acc + val;
});
var s2 = eval(magicnumber.join("+"));
//Display array element
document.getElementById("demo1").innerHTML = "Your data : " + data + "<br>";
document.getElementById("demo2").innerHTML = "Sum is: " + s1 + "<br>";
document.getElementById("demo3").innerHTML = "Sum is: " + eval(s2) + "<br>";
}
mymagicNumber();
<div id="demo1"></div>
<div id="demo2"></div>
<div id="demo3"></div>

How to format the element inside an array?

I have three arrays for example:
var name = ["wheel", "rectangle", "moon"];
var type = ["car", "shape", "sky"];
var all = [];
var temp = " ";
for (var i = 0; i < name.length; i++) {
temp = name[i] + " " + type[i];
all.push(temp);
}
for (var i = 0; i < name.length; i++) {
// I call here function to display all element of array `all`
}
The output is:
wheel car
rectangle shape
moon sky
But the format of output is not nice. I want to shift the element of array type before add them to array all, so I want the output to be like:
wheel car
rectangle shape
moon sky
My question is: how can I shift elements of the array to add them to another array and store them in a way that allows to me to display the elements like form above ?
But the form of output not nice
If you simply want to format the output in a better way, then try console.table
var name1 = [ "wheel","rectangle","moon" ];
var type = [ "car" , "shape", "sky"];
var all=[];
for (var i = 0; i< name1.length; i++)
{
all.push({ name : name1[i], type: type[i] });
}
console.table(all);
Try this fiddle to see the actual output since stack-snippet alters the behaviour of console api
You should calculate which is the longest string in the first array so to know in advance how many spaces you need to append to correctly pad the string
var n = ["wheel", "rectangle", "moon"];
var t = ["car", "shape", "sky"];
var all = [];
/* sorting the values of the first array by length desc,
* then get the length of the first element
*/
var padding = n.sort(function(a, b) {
return a.length <= b.length;
})[0].length + 1;
n.forEach(function(el, i) {
all.push(el + " ".repeat(padding - el.length) + t[i]);
});
Output
"rectangle car"
"wheel shape"
"moon sky"
codepen demo
First loop over the array and find the max length. Then loop again and add spaces.
<script >
var name=["wheel","rectangle","moon"];
var type=["car","shape","sky"];
var all=[];
var i=0;
var maxLength=0;
string temp=" ";
String.prototype.padLeft= function(len, c){
var r = '';
while(r.length < len) r += c;
return s+r;
}
for (i = 0; i< name.length; i++)
{
maxLength = Math.max(maxLength, name[i].length+type[i].length+1;
}
for (i = 0; i< name.length; i++)
{
temp=name[i]+type[i].padLeft(maxLength-name[i].length-type[i].length);
all.push(temp);
}
</script >
I would do as follows;
var id = ["wheel","rectangle","moon"],
type = ["car","shape","sky"];
id.longestStringLength = Math.max(...id.map(s => s.length));
type.longestStringLength = Math.max(...type.map(s => s.length));
id = id.map((s,_,a) => s + " ".repeat(a.longestStringLength-s.length));
type = type.map((s,_,a) => " ".repeat(a.longestStringLength-s.length) + s);
console.log(id,type);
Use \t instead of space while concatenating to make it aligned.
Why don't you just add tab '\t' and it will give you the desired output. Or you can append fixed number of spaces between the two array items.

LinQ foreach in javascript/jquery

How can I easily do these type of loops in Jquery or Javascript? Preferably without any other plugins.
string a = "";
foreach (var i in (from a in DbList1 select a.FieldA).Distinct())
{
a += i + ", ";
}
and this
foreach (var i in DbList2)
{
a += i.FieldB + ", ";
}
Loop number 2 could be solved like this atleast.
$.each(aData.DbList2, function (index, value) {
a += value.FieldB;
);
Not 100% sure this is the most effective though
You can use map method for iterating array variable.
Code snippets:
var arr = jQuery.map( aData.DbList2, function(value) {
return value.FieldB;
});
//To get unique array variable
var uniqueArr = [];
$.each(arr, function (i, el) {
if ($.inArray(el, uniqueArr) === -1) uniqueArr.push(el);
});
Second one is easy enough to do in vanilla JavaScript:
var a = "";
for (var i = 0; i < DbList2.length; i++){
a += DbList2[i].FieldB + ", ";
}
First one is a little trickier, but not impossible and can also be done with vanilla JS.
var a = "";
var uniques = [];
for (var i = 0; i < DbList1.length; i++ ){
var fieldA = DbList1[i].FieldA;
// check if we've already seen this value
if (uniques.indexOf(fieldA) < 0)
{
// Nope, record it for future use
uniques.push(fieldA)
// and update the string.
a += fieldA + ", ";
}
}

Match a range of rows in an array? jQuery, Javascript

I'm unsure how else to write the title but it's about as close as I can get to what I'm after.
I have a calculator I'm trying to create that compares values in a number of arrays.
Each data object in my array has 34 rows, some of which have the same number/value in them.
At the minute if you select france, I only want 1 of each grade to show in the dropdown, so the number 1 would appear once.
If you select France and grade 1, I want the outputted value to say the lowest value in that range to the highest, in this case USA would output 3 to 5 does this make sense?
If so I'm wondering how I'd possibly do this?
JSFiddle
http://jsfiddle.net/R85Qj/
Does this help?
http://jsfiddle.net/R85Qj/2/
$("#convert").on("click", function () {
var gradeIndex = $("#grade").val();
var gradeConversion = "";
/* gradeConversion += "<span>" + countryGrades[countryGradesIndex].country + ": " + countryGrades[countryGradesIndex].grades[gradeIndex][1] + "</span>";*/
var indexes = [];
var countryIndex = $("#country").val();
var gradeValue = countryGrades[countryIndex].grades[gradeIndex][0];
// find all indexes of gradeValue
for(var i = 0; i < countryGrades[countryIndex].grades.length; i++) {
if (countryGrades[countryIndex].grades[i][1] == gradeValue) {
indexes.push(i);
}
}
allValues = [];
for(var c = 0; c < countryGrades.length; c++) {
gradeConversion += countryGrades[c].country + ":";
for(i = 0; i < indexes.length; i++) {
if (i == 0 || countryGrades[c].grades[indexes[i]][1] != countryGrades[c].grades[indexes[i-1]][1]) {
gradeConversion += countryGrades[c].grades[indexes[i]][1] + " ";
}
}
}
$("#conversions").html(gradeConversion);
});

Each key value, join values inside loop

So i have a string, and I'm trying to join the content; if the val length is less than 10 chars, join it with the next value. But when i try this code, it joins with the same val instead of the next one.
//Set the regex.
myregex = /(<p>.*?<\/p>)/g;
//Variable string.
content = Example: <p>Hello</p><p>This is my test content</p><p>etc</p>
$(content.match(myregex)).each(function (key, val) {
var test = $(val).text();
if (test.length < 10) {
var n = val.concat(val);
$('#mydiv').append('<div>' + n + '</div>');
} else {
$('#mydiv').append('<div>' + val + '</div>');
}
})
This line here: val.concat(val), is indeed duplicating your content. What you need to do is grab the next value from the regex instead of the current one. Something like the following should work.
var matches = content.match(myregex),
myDiv = $('#mydiv');
for (var i = 0, len = matches.length; i < len; i++){
if (i + 1 < len && matches[i].length < 10){
myDiv.append('<div>' + matches[i].concat(matches[i+1]) + '</div>');
i += 1;
}
else myDiv.append('<div>' + matches[i] + '</div>');
}
val and val are the same thing, so of course val.concat(val) will duplicate it.
If you want to use $.each, I think it might be better to join with the previous value, because you don't know what the next one will be yet.
var previous = [];
$(content.match(myregex)).each(function (key, val) {
var test = $(val).text();
if (test.length < 10) {
previous = val;
} else {
if(previous.length) {
val = previous.concat(val);
}
$('#mydiv').append('<div>' + val + '</div>');
previous = [];
}
});

Categories

Resources