Appending a variable to an array without changing it - javascript

I'm currently working on a pre-bootcamp course and haven't been able to find help online in order to solve a problem that has me a bit confused.
I understand when we use JavaScript we have push(), pop(), shift() and unshift() methods we can use in order to add/remove from an array. The problem I'm running into is the test question ask:
1) Arrays appendKitten(name) appends a kitten to the kittens array and returns a new array,
leaving the kittens array unchanged:
I've been confused for nearly a day in solving this problem. I get when we do want to change the array we'll use one of the methods. For example when we append it'll be:
var kittens = ["Milo", "Otis", "Garfield"]
function destructivelyAppendKitten(name){
kittens.push(name)
return kittens
}
Which will push a new kitten(name) into the array. Now in order to solve the previous test I've written:
function appendKitten(name){
var newArray = []
var kittens = kittens.concat(newArray);
kittens.push(name)
return kittens
}
but continue to receive the same error. Is there something I'm missing?
My thought process in solving this question:
1- We are calling a function names appendKittens with a single argument -> name.
2- We are pushing data from the kitten variable into a local kitten instance in order to have the same array.
3- We push whatever name passes in the parameter into the new array.
4- Return the new array which had the push() performed leaving global kitten untouched.
Is my thinking process off? any ideas to where I'm off? All those who help. Thank you, really do appreciate it.

function appendKitten(name){
var newArray = kittens.slice();
// or ES6 way
// var newArray = [...kittens];
newArray.push(name)
return newArray
}

Related

How to add data to an array without push because it returns the length?

Simple. I have this array and I am trying to add a value to it but when I use push it just returns the length of the array after I push the value. I remember finding a way around this with a different function but I cannot remember what it was.
I will give a bit of context:
function submitCommentHandler() {
firestore.collection("posts").doc(title).update({
comments: comments.concat(newComment)
})
navigate("/all-posts");
}
There is the function to add a comment, but when I run that function it changes the value of comments in the firestore db to a number instead of the full array. If the value of the comments changes to a number I cannot access the text within the comments.
I decided to just do comments.push(newComment) and then set the comments to comments in the object. I think thats what some people were telling me.
When you use push() to add a value to an array, the value is pushed to the original array.
const values = [1];
const pushValue = values.push(2);
console.log(pushValue); // 2
console.log(values); // [1, 2]

Why push does not working with set methond in Map object

So very quick question here which I wasn't able to get sorted when searching google.
I have some code that works which has a Map object this.tweet and a (key,value) of (string,array). I push a value into the array and re-set Map object.
const newTweet = this.tweet.get(tweetName) || [];
newTweet.push(time);
this.tweet.set(tweetName, newTweet);
However, I am a minimalist freak and want a one-liner. When I want to add something to the array, I was wondering why I am not able to do this
this.tweet.set(tweetName, newTweet.push(time));
I keep getting a newTweet.push(time) is not a function error.
Thanks
Look at some documentation for push
The push() method adds one or more elements to the end of an array and returns the new length of the array.
Since you want to pass the array to set you can't use the return value of push.
You could create a completely new array instead:
const newTweet = this.tweet.get(tweetName) || [];
this.tweet.set(tweetName, [...newTweet, time]);

An Array of Related Data. Maybe array of ojects

I'm new to javascript but comming along good enough.
i have a project and i need to store alot of related data.
e.g. Full name, DOB, age, height,etc.
my idea after seeing objects was to have an array of object.
that's the idea but i found no good information online that would help me execute this.
basically were my idea came from was structs in C that i treat as records.
so i'd have and array of structs in c and the rest is self explanitory.
but i was to store the related data together like how i'd store data with a struct array.
please keep in mind unknown amount of entries
EDIT:
i found a simpler method that seem to work compare to the complicated things i'm getting as a starter.
var array= [];
function dosomething(){
for(var i=0;i<whateverNumber;i++){
array[i] = {name: "Delano", age:19, so on so forth}
}
}
You can simply create a variable and then start pushing the object into your array something like this
var obj = {id:1,age:26,name:"jhon doe"};
var obj2= {id:2,age:24,name:"jhon doe2"};
var arr = []
arr.push(obj,obj2)
console.log(arr)
and to remove the last object from your array of object simply use arr.pop()

Javascript array becomes an object structure

I'm experiencing an odd behavior (maybe it isn't odd at all but just me not understanding why) with an javascript array containing some objects.
Since I'm no javascript pro, there might very well be clear explanation as to why this is happening, I just don't know it.
I have javascript that is running in a document. It makes an array of objects similar to this:
var myArray = [{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...];
If I print out this array at the place it was created like JSON.stringify(myArray), I get what I was expecting:
[{"Id":"guid1","Name":"name1"},{"Id":"guid2","Name":"name2"},...]
However, if I try to access this array from a child document to this document (a document in a window opened by the first document) the array isn't an array any more.
So doing JSON.stringify(parent.opener.myArray) in the child document will result in the following:
{"0":{"Id":"guid1","Name":"name1"},"1":{"Id":"guid2","Name":"name2"},...}
And this was not what I was expecting - I was expecting to get the same as I did in teh parent document.
Can anyone explain to me why this is happening and how to fix it so that the array is still an array when addressed from a child window/document?
PS. the objects aren't added to the array as stated above, they are added like this:
function objTemp()
{
this.Id = '';
this.Name = '';
};
var myArray = [];
var obj = new ObjTemp();
obj.Id = 'guid1';
obj.Name = 'name1';
myArray[myArray.length] = obj;
If that makes any difference.
Any help would be much appreciated, both for fixing my problem but also for better understanding what is going on :)
The very last line might be causing the problem, have you tried replacing myArray[myArray.length] = obj; with myArray.push(obj);? Could be that, since you're creating a new index explicitly, the Array is turned into an object... though I'm just guessing here. Could you add the code used by the child document that retrieves myArray ?
Edit
Ignore the above, since it won't make any difference. Though, without wanting to boast, I was thinking along the right lines. My idea was that, by only using proprietary array methods, the interpreter would see that as clues as to the type of myArray. The thing is: myArray is an array, as far as the parent document is concerned, but since you're passing the Array from one document to another, here's what happens:
An array is an object, complete with it's own prototype and methods. By passing it to another document, you're passing the entire Array object (value and prototype) as one object to the child document. In passing the variable between documents, you're effectively creating a copy of the variable (the only time JavaScript copies the values of a var). Since an array is an object, all of its properties (and prototype methods/properties) are copied to a 'nameless' instance of the Object object. Something along the lines of var copy = new Object(toCopy.constructor(toCopy.valueOf())); is happening... the easiest way around this, IMO, is to stringency the array withing the parent context, because there, the interpreter knows it's an array:
//parent document
function getTheArray(){ return JSON.stringify(myArray);}
//child document:
myArray = JSON.parse(parent.getTheArray());
In this example, the var is stringified in the context that still treats myArray as a true JavaScript array, so the resulting string will be what you'd expect. In passing the JSON encoded string from one document to another, it will remain unchanged and therefore the JSON.parse() will give you an exact copy of the myArray variable.
Note that this is just another wild stab in the dark, but I have given it a bit more thought, now. If I'm wrong about this, feel free to correct me... I'm always happy to learn. If this turns out to be true, let me know, too, as this will undoubtedly prove a pitfall for me sooner or later
Check out the end of this article http://www.karmagination.com/blog/2009/07/29/javascript-kung-fu-object-array-and-literals/ for an example of this behavior and explanation.
Basically it comes down to Array being a native type and each frame having its own set of natives and variables.
From the article:
// in parent window
var a = [];
var b = {};
//inside the iframe
console.log(parent.window.a); // returns array
console.log(parent.window.b); // returns object
alert(parent.window.a instanceof Array); // false
alert(parent.window.b instanceof Object); // false
alert(parent.window.a.constructor === Array); // false
alert(parent.window.b.constructor === Object); // false
Your call to JSON.stringify actually executes the following check (from the json.js source), which seems to be failing to specify it as an Array:
// Is the value an array?
if (Object.prototype.toString.apply(value) === '[object Array]') {
//stringify

JavaScript methods not working on copied array

I can't figure out what's going on here... I'm trying to copy an array, and then shuffle and join the copy, but it just isn't cooperating.
I have a JS file and am initializing a new array at the top:
var myArray = [];
On load of this JS file, I am pulling data from the Facebook API and stickin' the results in myArray with some HTML around it.
I then have a function which I call on button click which creates a new variable from myArray and then joins and prints out the text in a div element:
var namesList = myArray;
namesList.join('');
$('#my_div').text(namesList);
It's obviously been simplified, but the premise is the same.
My problem is, the array is not joining like it should. It remains in array form and nothing I've tried has fixed this. I've also tried:
var namesList = myArray.slice();
and
var namesList = myArray.slice(0);
to no avail.
HOWEVER: I can manipulate myArray with no problems in the same function and get the results I need. The problem with that is, I need to be able to shuffle the array each time the function is called and then print it out as text; this is why I am copying it in the first place.
For the life of me I can't figure out why this isn't working. All I need to do here is to create a copy of the variable within the scope of the function I'm calling, shuffle it, join it, and print it.
How do I fix this? OR, is there a better alternate? Many thanks in advance!
The join() method returns a string rather than modifying the array reference - you need to change your code to this:
var namesList = myArray;
namelist = namesList.join('');
$('#my_div').text(namesList);
That's because namesList still is an array. join() returns a string, which you should use:
var namesList = myArray.join('');
$('#my_div').text(namesList);
namesList.join('');
This joins the array then throws the result away. You want
namesList = namesList.join('');

Categories