I'm new to javascript and currently working my way through code school. I've done this exercise before and have no issue with it, but after not doing anything for a week i decided to go back and redo some of the exercises... now i'm stuck on this one :( here is the instructions and below that is my code... what I'm I doing wrong code school tells me I'm not adding white space between the two words?
Now alert to the screen the entire first movie in eightiesMovies, but only using the >eightiesMovies variable. For now, use the concatenation operator to unite the words into one >string. Remember to be attentive to necessary whitespace…
var movie1 = [ 16, "Candles"];
var movie2 = [ 3, "Men", "and", "a", "Baby"];
var eightiesMovies = [ movie1, movie2];
my code
alert(eightiesMovies[0,1] + " " + eightiesMovies[0,1]);
To access an array in an array, you use two sets of brackets after each other:
alert(eightiesMovies[0][0] + " " + eightiesMovies[0][1]);
(Also you were using the same item twice instead of two items.)
What's happening in your original code is that you are accidentally using the comma operator, that's why you don't just get a syntax error for that code. An expression like 0,1 will evaluate both 0 and 1, and then the value of the expression is the last value. That will make the code access eightiesMovies[1] which is an array, and the string concatenation would convert the array to a string. The result is "3,Men,and,a,Baby 3,Men,and,a,Baby" rather than the "16 Candles" that is expected.
To join the elements of an array to form a string use join()
in your example
eightiesMovies[0].join(" ");
Related
to understand the split method I went over this link https://www.w3schools.com/jsref/jsref_split.asp
but not sure why comma not adding after 3 and why empty array not showing up in the output
is it just doing array concatenation
i debugged but not sure
can you guys let me know.
[123] + [] + 'foo'.split('');
"123f,o,o"
When the array is converted to string. Implicitly join() is called on it. So [].join() is '' that's why it doesn't show up in string.
But if you use some empty elements then it will show ,
console.log([123] + [,] + 'foo'.split(''));
How to concat arrays:
There can be different ways to concat two or more arrays. The modern one is using Spread Operator.
console.log([...[123], ...[],...'foo'.split('')]);
I have an object with strings in it.
filteredStrings = {search:'1234', select:'1245'}
I want to return
'124'
I know that I can turn it into an array and then loop through each value and test if that value in inside of the other string, but I'm looking for an easier way to do this. Preferably with Lodash.
I've found _.intersection(Array,Array) but this only works with Arrays.
https://lodash.com/docs#intersection
I want to be able to do this without having to convert the object to an array and then loop through each value because this is going to be potentially holding a lot of information and I want it to work as quickly as possible.
Thank you for you help.
Convert one of the strings (search) to a RegExp character set. Use the RegExp with String#match on the other string (select).
Note: Unlike lodash's intersection, the result characters are not unique, so for example 4 can appear twice.
var filteredStrings = {search:'1234', select:'124561234'}
var result = (filteredStrings.select.match(new RegExp('[' + filteredStrings.search + ']', 'g')) || []).join('');
console.log(result);
i would like to convert this string:
'[
['Row1 of first array', 'Row2 of first array'],
['Row1 of 2nd array', 'Row2 of 2nd array']
]'
Into an array with three arrays of one dimension and two items.
My expected output is an array with 2 elements:
Array 1
Array 2
And every array has two elements inside.
Is there any in Jquery to do this conversion?
That's not a valid string -- you're nesting single quotes inside of single quotes. However, if you convert the string into one using double quotes on the inside:
str = '[ ["Row1 of first array", "Row2 of first array"], ["Row1 of 2nd array", "Row2 of 2nd array"] ]'
then you could simply parse it as a JSON object:
arr = $.parseJSON(str); // returns a two-dimensional array
This is far, FAR safer than using eval, which should only be done when you know EXACTLY what's inside the string, and even then, it's a sign of a lazy developer. When using parseJSON, you know that you're getting either an object or an array when you're done -- when using eval, anything might happen.
I guess eval will work:
var str = eval("[['Row1 of first array', 'Row2 of first array'],['Row1 of 2nd array', 'Row2 of 2nd array']]");
console.log(str);
Ive got a really strange problem with some javascript code that ive written. I have set this code to execute on load. The idea of it is to remove a value from a text field if it is listed in another field. Here is the code:
var diseases = document.getElementById("AffectedBy").value;
var diseasearray = diseases.split("-");
alert("disease array size: " + diseasearray.length);
for (i=0;i<diseasearray.length;i++)
if (diseases.match("-" + diseasearray[i]))
{
diseasearray[i] = "-" + diseasearray[i];
alert(diseasearray[i]);
document.getElementById("DiseaseNotSelected").value=document.getElementById("DiseaseNotSelected").value.replace(diseasearray[i],"")
}
This code above gives an array size of 3 (1 blank, and 2 values) but when I display the values in the alert it only shows 2 values(1 blank, and 1 value)
This piece of code:
var foods = document.getElementById("FoodFor").value;
var foodarray = foods.split("-");
alert("food array size: " + foodarray.length);
for (i=0;i<foodarray.length;i++)
if (foods.match("-" + foodarray[i]))
{
foodarray[i] = "-" + foodarray[i];
alert(foodarray[i]);
document.getElementById("FoodNotSelected").value=document.getElementById("FoodNotSelected").value.replace(foodarray[i],"")
}
This code above gives an array size of 3 (1 blank, and 2 values) and when I display the values in the alert it only shows 3 values(1 blank, and 2 value).
Can anyone see a reason why the first code block only shows 2 items in the array as I cant see why and its really bugging me now.
the first one is running a match against a string starting with '-'.
I don't have your actual values, but let's say that the value of #AffectedBy is "test1-test2-test3".
the first alert will be 3, because the diseasearray will have three components (test1, test2, test3)
you then run through a loop (0, 1, 2).
The first one will fail, as there is no "-test1" in the string, but the other two will succeed, as there are "-test2" and "-test3" substrings.
As I said in my comment above: beware that whatever you pass into match will get turned into a regular expression. If that contains some special character, it might not match where you would expect it to (or vice versa).
The string White Spot (Ich) will be turned into the regex /White Spot (Ich)/; which does not match White Spot (Ich) but does match White Spot Ich, since the parentheses are grouping operators in a regex.
Change the regular expression test
diseases.match("-" + diseasearray[i])
into the plain string comparison
diseases.indexOf("-" + diseasearray[i]) !== -1
and you should be set.
(I think. :-)
First, for the length you need to do for example foodarray.length -1.
How many items do you have in your array (suppose to have)? We need more explanation
i need to get part of string into variable. (note, i will always use exactly 4 names)
var names = "Andrew Peter Bob Mark"
I need to get the last one to
var last = "Mark"
Thanks for help in advance
var last = names.split(/\s+/).pop(); // "Mark"
Explanation: .split splits a string on a given separator and returns an array. /\s+/ is a regular expression for "one or more whitespaces" (space, tab, newline, etc). .pop() grabs the last value from the array that .split returns.
Answer from Roatin Marth is correct, but in case if you need 4 times faster version (in IE) of same operation:
var last = names.substr(names.lastIndexOf(" "));
It is working without regular expressions and temp arrays - just with index operations of string.