Does .join method change the array into string in Javascript? - javascript

The result for .join is different from .push or .pop.
var mack=[];
mack.push("dog", "cat");
mack.join(" ");
alert(mack);
Console.log: ["dog", "cat"]
var mack=[];
mack.push("dog", "cat");
alert(mack.join(" "));
Console.log: "dog cat"
In the first one, mack.join(" "); does not change the original mack array, unlike mack.push("dog", "cat"); or mack.pop();.
I'm curious that why this happened. And is there any other method like this?

The join() function doesn't change the element of array that's only represent the array elements as string with the separator what we give as argument.
here is the reference of join function
Array.prototype.join()
Array push and pop is use to add or remove element from a array that return array new size for push and element for POP.
Array.prototype.push()
Array.prototype.pop()
Here the array elements are ok as you pushed on it.
var mack=[];
mack.push("dog", "cat");
var mack_string = mack.join(" ");
console.log(mack); // Array [ "dog", "cat" ]
console.log(mack_string); // "dog cat"

Push and pop methods are used on Array object to add or remove data to/from Array and therefore change Array itself.
Join method doesn't change Array, it returns String - new object, Array remains unchanged as it is. It could be used e.g. for concatenating Strings which are put in array with particular character.
More about arrays could be found here: http://www.w3schools.com/js/js_array_methods.asp

The join() method joins all elements of an array into a string, detail
It returns a string and does not modify the original array.
Also it does not make sense to assign String for Array object, if that was your expectation.

Related

In javascript how to replace elements of an array to it's corresponding values in another object?

I have the mapping of abbreviation and full name as follow:
object = {"TSLA":"TESLA INC.","GOOG":"GOOGLE INC.","APPL":"APPLE INC.","AMZN":"AMAZON CORPORATION", "MSFT":"MICROSOFT CORPORATION"}
as an output of function i get the following array:
array = ["AMZN","APPL"]
I want to display the values of the associated keys as follows:
output_array = ["AMAZON CORPORATION", "APPLE INC."]
Note that, the actual object has more key: value pairs
Using IndexOf() I can replace one value. However, I believe there must be a way of mapping the array elements to replace the values at once.
Since I am new to JS, I would appreciate any suggestion.
array.map(abbr => object[abbr]) does the job; it iterates over the array rather than the object, which is more efficient as the object already is a lookup table with the right keys - you are right, there is no need to use indexOf which uses a linear search.

Array length is not correct in javascript

I have an array like below
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
but i am getting length as 2 when i do console.log(arr.length) even though i am able to console all the values .
and not able to get all values while doing console.log(JSON.stringify(arr))
What is the issue here.
here is the link to fiddle fiddle
.length is a special property in Javascript arrays, which is defined as "the biggest numeric index in the array plus one" (or 2^32-1, whatever comes first). It's not "the number of elements", as the name might suggest.
When you iterate an array, either directly with for..of or map, or indirectly with e.g. JSON.stringify, JS just loops over all numbers from 0 to length - 1, and, if there's a property under this number, outputs/returns it. It doesn't look into other properties.
The length property don't work as one will expect on arrays that are hashtables or associative arrays. This property only works as one will expect on numeric indexed arrays (and normalized, i.e, without holes). But there exists a way for get the length of an associative array, first you have to get the list of keys from the associative array using Object.keys(arr) and then you can use the length property over this list (that is a normalized indexed array). Like on the next example:
arr=[];
arr[0]={"zero": "apple"};
arr[1]={"one": "orange"};
arr["fancy"]="what?";
console.log(Object.keys(arr).length);
And about this next question:
not able to get all values while doing console.log(JSON.stringify(arr))
Your arr element don't have the correct format to be a JSON. If you want it to be a JSON check the syntax on the next example:
jsonObj = {};
jsonObj[0] = {"zero": "apple"};
jsonObj[1] = {"one": "orange"};
jsonObj["fancy"] = "what?";
console.log(Object.keys(jsonObj).length);
console.log(JSON.stringify(jsonObj));
From MDN description on arrays, here, "Arrays cannot use strings as element indexes (as in an associative array) but must use integers."
In other words, this is not Javascript array syntax
arr["fancy"]="what?";
Which leads to the error in .length.

Javascript slice isn't giving me correct array length values

Why does it say length 1 instead of 4?
The following is what I'm trying to push and slice. I try and append items.image_urls and slice them into 5 each.
items.image_urls is my dictionary array.
var final_push = []
final_push.push(items.image_urls.splice(0,5))
console.log(final_push.length)## gives me 1...?
var index = 0
final_push.forEach(function(results){
index++ ##this gives me one. I would need 1,2,3,4,5,1,2,3,4,5. Somehting along that.
}
items.image_urls looks like this:
It's an iteration of arrays with image urls.
In your example items.image_urls.splice(0,5) returns an array of items removed from items.image_urls. When you call final_push.push(items.image_urls.splice(0,5));, this whole array is pushed as one item to the final_push array, so it now looks like [["url1", "url2", "url3", "url4", "url5"]] (2-dimensional array). You can access this whole array by calling final_push[some_index].
But what you want instead is to add every element of items.image_urls.splice(0,5) to the final_push. You can use a spread operator to achieve this:
final_push.push(...items.image_urls.splice(0,5));
Spread syntax allows an iterable such as an array expression or string
to be expanded in places where zero or more arguments (for function
calls) or elements (for array literals) are expected
This is exactly our case, because push() expects one or more arguments:
arr.push(element1[, ...[, elementN]])
And here is an example:
let items = {
image_urls: ["url1", "url2", "url3", "url4", "url5", "url6", "url7", "url8", "url9", "url10"]
};
let final_push = [];
final_push.push(...items.image_urls.splice(0,5));
console.log(final_push.length);
console.log(JSON.stringify(final_push));
console.log(JSON.stringify(items.image_urls));
Note: do not confuse Array.prototype.slice() with Array.prototype.splice() - the first one returns a shallow copy of a portion of an array into a new array object while the second changes the contents of an array by removing existing elements and/or adding new elements and returns an array containing the deleted elements.
That seems to be a nested array. So if you would access index 0, and then work on that array like below it will probably work:
console.log(final_push[0].length); //should print 4
The author is mixing up splice and slice. Probably a typo :)
You start at the beginning (0) and then delete 5 items.

Using method sort() for sorting symbols in element of array

I need to sort an element cinema of array arr by symbols unicode (in the output it must been like "aceinm"). I know that in this case we need to use method sort(). But I do know how inject sort method for array element.
Please, help. Code below are not working.
Error: arr[1].sort is not a function.
var arr = ["cinema"];
arr[1].sort();
console.log(arr[1]);
If you want to sort your string, you can easily do this by splitting and joining the string.
"cinema".split ("").sort ().join ("")
// aceimn
Or, in your case:
arr[0] = arr [0].split ("").sort ().join ("")
// arr: ["aceimn"]
If you need to sort all strings in an array, use map ().
arr = arr.map (itm => itm.split ("").sort ().join (""))
You are referring arr[1] which is not available also you have to split in order to sort the letters.
var arr = ["cinema"];
var sorted = arr[0].split('').sort();
console.log(sorted, sorted.join(''));
This should do what you want:
var arr = ["cinema"];
console.log(arr[0].split("").sort().join(""));
EDIT: I see the same solution has been proposed by several others. I'll expand a bit on it.
Since you want to sort by the letters in the word cinema, and cinema is at index 0, you get the string "cinema" by calling arr[0], and then split the string with the method .split(""). This turns the string into an array that you can .sort() in the way you attempted initially.
The error you got, "Error: arr[1].sort is not a function", tells you that .sort() is not a function of the string element. Once you've turned the string into an array (for example with .split()), the .sort() function becomes available.

What does empty array.slice(0).push(anything) mean?

I want to clone a new array from an existing one and push in an element.
Unfortunately, the existing array is an empty one, so it's like:
[].slice().push(65)
the output of above expression is 1.
Why is it 1?
Array#push() returns the length of the resultant array. Since you're pushing a single value onto an empty array, the length of the result will indeed be 1.
If you want to see the updated array as output, you'll need to save a reference to it since push() does not return a reference:
var arr = [].slice();
arr.push(65);
console.log(arr); // [ 65 ]
Changing my comment to an answer:
MDN push(): The push() method adds one or more elements to the end of an array and returns the new length of the array.
You need to do it in two steps, not one with that pattern.
var temp = [].slice();
temp.push(65);
console.log(temp);
If you want to do it in one line, look into concat()
var a = [1,2,3];
var b = [].concat(a,64);
console.log(b);

Categories

Resources