single popup window of only certain array values. javascript - javascript

Hi im trying to make a single popup window consisting of only values in the array that are larger/ smaller than a certain number. How can I go about doing this?
<script>
var moe = [3,3.14,4.3,8,9,19,23,24,46,54,87];
var noe = moe.indexOf(23);
function myFunction()
{
alert(noe);
}
function compare(){
for (var i=0;i<moe.length;i++){
if (moe[i]>10){
alert(moe[i]);
}
}
}
</script>

Like so:
function compare(){
var out = [];
for (var i=0;i<moe.length;i++){
if (moe[i]>10){
out.push(moe[i]);
}
}
alert(out.join());
}

Lets walk through the problem:
Given an array of values: values = [3,3.14,4.3,8,9,19,23,24,46,54,87];.
We want to filter the result based on the value being larger than 10.
Finally output the result in an alert dialog box (which takes a string).
Step one is to work out the filtering and then how to turn the result into a string to apps to the alert() function.
(function() {
var i, len, values, value, results, string_value;
values = [3,3.14,4.3,8,9,19,23,24,46,54,87];
results = []; // Empty array which we will build in order during the filter
for (i = 0, len = values.length; i < len; i++) {
value = values[i]; // Not needed; used for readability
if (value > 10) {
results.push(value); // Add this value to the results array
}
}
// Now that we have a result lets convert that to a string
string_value = results.join(", ");
// And output the result with some string concatenation
alert("Filtered results: [ " + string_value + " ]");
// The use of string_value is optional, you could in-line
// this into the alert line
})();

Related

How could I add variables according to the length of the array?

I have an array that the values ​​range from A to Z, which I want to convert to variables that depend on the input data, for example:
enter the data
362,232,113 and this becomes an array of a length of 3 unit.
so I want to assign the name of a variable depending on the length of the input array but when executing the code, it assigns the array index well, but that same index executes the length of the input array and does not assign the variables as I would like it to.
in fact when executing this happens:
(3) 326
showing that the matrix was correctly divided but the same index was executed 3 times, in summary what I want is to be executed as follows:
"A = 326" "B = 232" "C = 113"
In advance I thank you for your help
var asignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
matrix =[326,232,113];
function divide(){
xyz = matrix.split(",");
console.log(matrix);
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
console.log(A); //(2) 326
}
}
You have a typo assignLetter instead of asignLetter ( two s ) and you need to pass a string to your function for it to work :
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
window[assignLetter[i]] = xyz[i];
}
}
console.log({A,B,C});
You should avoid creating global variabels like that, have them in an object instead
var assignLetter = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","Z","X","Y","Z"];
var myVars = {};
divide("326,232,113")// input data
function divide(matrix){
xyz = matrix.split(",");
for(var i = 0;i < xyz.length; i++){
myVars[assignLetter[i]] = xyz[i];
}
}
console.log(myVars);
I think you want to pass the parameters 326,232,113 as a whole string. You're passing them as parameters wrong.
So just do the same thing you're doing but like this: divide("326,232,113")

Javascript Array ES6 Undefined Error

I'm having trouble solving this question (the result is always undefined) and I am not sure what I'm doing wrong... any ideas?
Write a function that takes a number and generates a list from 0 to that number.
Use the function to assign a value to the myNumberList variable so that it has the value of a list going from 0 to 5.
Assign a value to the variable secondLastItem that should be the second last item of the myNumberList array.
function listMaker(listLength) {}
var myNumberList = null; // replace with number list created by listmaker
var secondLastItem = null; // replace with second last item
You can try the following way using ES6's spread operator (...):
function listMaker(listLength) {
return [...Array(listLength).keys()];
}
var myNumberList = listMaker(10);
// If you want the specified number passed as argument to be included as the last item in the array then push it.
myNumberList.push(10);
console.log(myNumberList);
Here is one way to write it:
function listMaker(number) {
var secondToLast;
var list = [];
for (var i = 0; i <= number; i++){
list.push(i);
}
secondToLast = list[list.length - 2];
return [list, secondToLast]
}
var list = listMaker(5)[0];
var secondToLast = listMaker(5)[1]
console.log(list + "\n" + secondToLast);
That is the snippet ^
Here is the jsfiddle

Remove duplicates in array separated by double commas in JavaScript

I have an array in JavaScript like this
var data = [,A_1_VII,VII,V2,,A_1_VII,VII,V2,,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
when I alert in JavaScript it gives as below
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
But I want like this which is duplicates removed array
var unique_data = [,A_1_VII,VII,V2,,B_1_XIV,XIV,V3,,B_2_XVI,XVI,V3]
On alert it should give like this
,A_1_VII,VII,V2
,B_1_XIV,XIV,V3
,B_2_XVI,XVI,V3
First Thing your array contains string as a constant that's not going to work.
Secondly, if all of you value are strings you can do it as follows:
var data =[,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV","XIV","V3",,"B_2_XVI","XVI","V3"];
var uniqueArray = data.filter(function(item, pos) {
return data.indexOf(item) == pos;
})
alert(uniqueArray);
Assuming the variables in your array are well defined, you can clean it up and remove duplicates with a for loop:
var data [/* ... */];
var unique_data = [];
for(let i = 0; i < data.length; i++) {
if (data[i] && unique_data.indexOf(data[i]) === -1) {
unique_data.push(data[i]);
}
}
Please note that the code above assumes that your array contains non-object types, otherwise the solution would need to use something more sophisticated than indexOf().
You can create your unique function to remove duplicate entry and empty value from array like this.
var data =[,"A_1_VII,VII","V2,,A_1_VII","VII","V2",,"A_1_VII","VII","V2",,"B_1_XIV,XIV","V3",,"B_2_XVI,XVI,V3"]
var unique_data = uniqueList(data);
alert(unique_data);
function uniqueList(list) {
var uniqueResult = [];
$.each(list, function(i, e) {
if ($.inArray(e, uniqueResult) == -1 &&$.inArray(e, uniqueResult)!="")// chech for unique value and empty value
uniqueResult.push(e);
});
return uniqueResult ;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Not able to compare variables in JQuery

I have an array of records. I want to search a string at the specific position of the array. But some how I am not able to do so. Kindly see the code below:
var match_index = [];
var count = 0;
var keyword1 = csvvalue[1][9].replace(/\"/g, '');
var search_text="इलाहाबाद";
$("#leng").html(csvvalue.length);
for(var i=0; i<csvvalue.length; i++){
$("#index").html("loop");
var keyword1 = csvvalue[i][9].replace(/\"/g, '');
if (search_text === keyword1)
{
match_index[count] = i;
count++;
$("#index").html("match");
}
$("#index").append("<br />" + i.toString());
}
In the above code, the control is is not going inside the if statement, though the string is available in the array at index 1 and 2. Also only the last value of i is getting printed (last line of the code) though it should print all the values of i starting from 0.
My actual requirement is to search through entire array for a specific string. I have changed the code to suit my requirement better.
Edited
I tried every thing but the control is not going inside the if statement though there are two matching records
You are comparing two values set before the loop
I guess it should be more like :
var match_index = [];
var count = 0;
var keyword1 = "";
var search_text="इलाहाबाद";
$("#leng").html(csvvalue.length);
for(var i=0; i<csvvalue.length; i++){
keyword1 = csvvalue[i].replace(/\"/g, '');
$("#index").html("loop");
if (search_text === keyword1)
{
match_index[count] = i;
count++;
$("#index").html("match");
}
$("#index").append("<br />" + i.toString());
}
Or depending on how your csvvalue array is structured.
keyword1 = csvvalue[1][i].replace(/\"/g, '');
Why loop through the whole array if you want to check a specific variable in the array.
You could just do something like
if (search_text === csvvalue[1][9].replace(/\"/g, '') {
//do something
}
Unless you really need to know how many times you run through the array.

jquery split() issue

Hopefully this is easy for someone.
I have a set of checkboxes with values 1,2,3 etc with the same name attribute (cp_bundle).
I use the following code to get a comma-delimited list of those checkboxes.
var hl_calling_plan_bundle = $('input[name="cp_bundle"]:checked').getCheckboxVal() || "";
jQuery.fn.getCheckboxVal = function(){
var vals = [];
var i = 0;
this.each(function(){
vals[i++] = jQuery(this).val();
});
return vals;
}
if I check the first and third checkboxes, the following will be returned:
1,3
Then, I want to run a test to see whether a particular value (e.g. "3") exists in the the returned variable
But, I can't get past the split of the variable using the following:
var aCallingBundle = hl_calling_plan_bundle.split(",");
This gives the error:
hl_calling_plan_bundle.split is not a function
Any idea what's going on?
hl_calling_plan_bundle is an array. You have to use array operations on it, not string operations.
If you want to know if the value 3 is in the array, then you have to search the array for it. There are many ways to search an array, but since you have jQuery, it's easy to use the .inArray() function:
var index = $.inArray(3, hl_calling_plan_bundle);
if (index != 1) {
// found 3 in the array at index
}
Incidentally, you may want to simplify your function like this:
jQuery.fn.getCheckboxVal = function(){
var vals = [];
this.each(function(){
vals.push(this.value);
});
return vals;
}
or this way:
jQuery.fn.getCheckboxVal = function(){
return(this.map(function(){return(this.value)}).get());
}
split() is a String method, it does not exist on an Array.
When you say the following is returned 1,3, you may be implicitly calling the String's toString() method, which will by default join() the array members with a comma. If you explicitly called toString(), then you could call split(), but that would be an anti pattern.
You don't need to split the string, you can just use RegEx to search:
var str = '1,3,22,5';
/\b1\b/.test(str); // true
/\b2\b/.test(str); // false
/\b3\b/.test(str); // true
/\b5\b/.test(str); // true
/\b22\b/.test(str); // true
Making it a function:
String.prototype.findVal = function(val){
var re = new RegExp('\\b' + val + '\\b');
re.lastIndex = 0;
return re.test(this);
};
str.findVal(2); // false
str.findVal(22); // true
To get the checkboxes:
var cbs = document.getElementsByName('cp_bundle');
To get arrays of all values and the checked values:
var allValues = [];
var checkedValues = [];
for (var i=0, iLen=cbs.length; i<iLen; i++) {
if (cbs[i].checked) checkedValues.push(cbs[i].value);
allValues[i] = cbs[i].value;
}

Categories