new Array(5).toString() returning four commas - javascript

to understand the below code snippet I looked at this link.
But still I am not able to figure it out why its printing four commas in the console.
since I am creating array of five items
can you tell me how its working.
new Array(5).toString();
",,,,"

Imagine what it would look like with values in each of the array indexes.
[1,2,3,4,5].join(); // Returns 1,2,3,4,5
Now if you remove the numbers, you're just left with the commas in the middle.
new Array(5).join(); // Returns ,,,, because the values are blank.

toString() method iterates throw all elements in the Array push them into string and push , betweeen them.
As you defined empty Array with 5 elements, when you apply toString it convert it to five "empty" strings with 4 "," between them

new Array(5)returns a sparse array or an array with 5 empty spaces inside. The only thing that this does is to set the length property of the array object to the specified argument (5 in this case).
console.log(new Array(5)) // browser console --> [empty × 5]
So naturally if you attempt to print its contents it would show you that you have 5 empty spaces separated by ,
console.log(new Array(5).toString()) // ,,,, <-- 5 empty ',' separated elements

As you can see, someArray.toString() will return what is inside the array but without [ and ].
console.log([1,2,3,4,5])
console.log([1,2,3,4,5].toString())
So, if you have noting in the array element, it will return empty string and only print the comma. (Array(5) is the same as [,,,,,])
console.log([,,,,])
console.log([,,,,].toString())
Array(5) will return an array only with the property length: 5. Wich will make it's elements undefined.
If you want to make it something else then undefined you can use .fill
console.log(Array(5))
console.log(Array(5).fill(""))
console.log(Array(5).fill("anything"))

Related

Unexpected Output from Array() Method

I have this snippet of code below and don't quite understand the output
function repeatStringNumTimes(str, num) {
if (num <0) {
return ""
} else {
return Array(num+1).join(str)
}
}
console.log(repeatStringNumTimes("abc", 3));
I would have expected the output to be "abcabcabc" though if I console.log(repeatStringNumTimes("abc", 3)) in JS Bin it produces "abcabc"?
If I specify Array(3) - Would it not concatenate the string 3 times? Why only 2 in this instance?
If I specify Array(3) - Would it not concatenate the string 3 times?
Why only 2 in this instance?
console.log([1,2,3].join('abc'))
// outputs 1abc2abc3
Note that 'abc' is the separator for the join between the 3 elements, and so it appears twice, not 3 times.
Therefore, if you create an empty array, it shows 'abc' twice, separating 3 empty strings:
console.log(Array(3).join('abc'))
// outputs abcabc
Also note that there is String.repeat()
console.log('abc'.repeat(3))
// outputs abcabcabc
look when i run your code the right output appears so your code has no bugs, and when you specify Array(3) the output will be "abcabc" your code is working well
If you will have a look into the Array#join documentation, It will join the array items based on the passed separator in the join method. Ideally, It will not consider the join before the first and after the last element in an array.
console.log(Array(3)) // [undefined, undefined, undefined]
console.log([undefined, undefined, undefined].join('abc')); // 'abcabc'
As you want to fill the array with the string, Correct method is Array#fill which changes all elements in an array to a static value, from a start index (default 0) to an end index (default array.length) and then join the elements from an array with the help of Array.join() method.
console.log(Array(3).fill('abc').join(''));

How can I make sure Javascript array containing values with certain character remain unaltered, while I work on it?

Suppose I have an Javascript array,
var example = [and, there,sharma<br, />, ok, grt]
Now I want to randomly delete some array values - but not those values which have
<br
in them, in the above example, I want to make sure
"sharma<br" is not deleted.
I also do not want to delete "/>".
Can anyone help me. I would really appreciate the answer.
First of all, that is not a valid array, unless you are missing the string quotes. Anyway, what you are searching for is Array.Filter. In your case :
var filtered = example.filter(v => v.indexOf("<br") != -1 || v.indexOf("/>") != -1)
If I have understood the problem correctly, then you want to keep those entries in the array which have substrings "<br" and "/>"
If thats the case, you can try using javascript string method includes() to see if a string contains a particular substring.
JavaScript array must be created as below
var example = ["and"," there"",sharma<br","/>","ok"," grt"];
Using splice method , to delete the array values specifying the index positions.
array splice() method changes the content of an array, adding new elements while removing old elements.
Syntax
Its syntax is as follows −
array.splice(index, howMany, [element1][, ..., elementN]);
Parameter Details
index −
Index at which to start changing the array.
howMany −
An integer indicating the number of old array elements to remove. If howMany is 0, no elements are removed.
element1, ..., elementN −
The elements to add to the array. If you don't specify any elements, splice simply removes the elements from the array.
Return Value
Returns the extracted array based on the passed parameters.
var removed = arr.splice(2, 2);
This would remove your suggested output to be my assumption .

pushing to array element appended with single quote

the following varibale is evaluated and adding into array element, getting a single quote when array is printed, how to avoid this,here is the code
var t1 = "Date.UTC("+varDate[0]+','+varDate[1]+','+varDate[2]+")"
console.log(t1)
The Output is
Date.UTC(2001,1,23)
then added t1 to an array
diffArray.push(t1)
console.log(t1)
it appended single quote why ? how to avoid this ?
[ 'Date.UTC(2001,1,23)']
This is just console.log() showing you that the item in the array is a string. Your t1 variable has always been a string so there is no difference in the internal representation, just how console.log() chooses to display it.
If you do console.log(diffArray[0]), you will see the original representation without quotes just because that's what console.log() does when you give it a plain string. When you give console.log() an array, it puts quotes around any elements that are strings to indicate the difference between a string and some other type that the array might hold.
Look in your console for this jsFiddle: http://jsfiddle.net/jfriend00/yrannpm2/
console.log(t1); // Date.UTC(2001,1,23)
console.log(diffArray[0]); // Date.UTC(2001,1,23)
console.log(diffArray); // ["Date.UTC(2001,1,23)"]

How to concat an array within an array

Here is the problem. How do I do this below. The array within an array is throwing me off.
[...] 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];
I have tried these answers to no avail
alert(eightiesMovies[0][0].concat("", eightiesMovies[0][1]));
alert(eightiesMovies([0][0]).concat("", eightiesMovies([0][1]));
Very simple:
movie1.concat(movie2) // will combine the 2 arrays
movie2.join(''); will join the element in the array
result:
movie2.join('') => "3MenandaBaby"
eightiesMovies[0][0] + " " + eightiesMovies[0][1]
The concatenation operator in this case is +, which is used to concatenate strings together. Since this is a nested array, you can chain array access. You want the first movie (which is an array in the first element of the eightiesMovies array at position 0). Then just concatenate each value of that array. You would have to know the length of the arrays ahead of time. That is to say the above would only print out part of the second movie.

Code to get last 2 items from an array

Am trying to get last 2 items from an array
result.forEach(function (re) {
console.log(re.files)
// prints ["utilities.rb", "print_utilities.rb", "lities.rb", "agination.rb"]
});
i only want to last two elements in the array in the order
[ "agination.rb", "print_utilities.rb"]
How it is possible
Use the Array.prototype.slice method for this with a negative index.
From MDN:
As a negative index, begin indicates an offset from the end of the
sequence. slice(-2) extracts the last two elements in the sequence.
slice returns a new array, so you can store the result in a new variable.
So in your case, simply use:
var arrayWithLast2Items = re.files.slice(-2);
jquery provides a slice method for this
e.g
$([1,2,3]).slice(-2)
https://api.jquery.com/slice/
Have a temp array with size 2, iterate the elements of original array and over write/copy elements to the temp array.
Once iteration is complete, the temp array will contain last 2 elements of original array.

Categories