Learning to programming JavaScript, but I'm stuck - javascript

Yesterday I started learning JavaScript. I am using the system Codecademy, but I'm stuck. When I say "stuck", I mean I have assignment with which I cannot see what is wrong.
The assignment is:
Create an array, myArray. Its first element should be a number, its second should be a boolean, its third should be a string, and its fourth should be...an object! You can add as many elements of any type as you like after these first four.
This is the code I made:
var myObj = {
name: 'Hansen'
};
var myArray = [12,true, "Steen" ,myObj.name];
The error:
Oops, try again.
Is the fourth element of myArray an object?
Hope you can help me.

The problem with your fourth element is you are passing a string because myObj.name is defined as Hansen. Pass the object instead:
var myArray = [12,true, "Steen" ,myObj];

I don't know that site, but you can do:
var myArray = [
12,
true,
"Steen",
{name: 'Hansen'}
];
What you are passing to the array is the value of the name property of your object instead of the object itself.

Your passing in the name property instead of the object for the fourth array parameter as you probably already know from the other anwers.
As your learning here are a few ways to do exactly the same thing as your accomplishing here.
Your way corrected:
var myObj = {
name: 'Hansen'
};
var myArray = [12, true, "Steen", myObj];
Other ways:
// Method 1
var myArray = [12, true, "Steen", {name: 'Hansen'}];
// Method 2
var myObj = new Object();
myObj.name = "Hansen";
var myArray = new Array(12, true, "Steen", myObj);
// Method 3
var myObj = {};
myObj['name'] = 'Hansen'
var myArray = [
12, true, 'Steen', myObj
]
Each method shows a few different ways to do the same thing, you can mix and match the equivalent parts of code to get the same job done. It's basically inter changing between the normal JavaScript syntax and object literal syntax.

Related

Angular / Javascript search array for object key

For the purpose of example lets have the following object:
var myobj = {id: 1, text: 'hello world', user_id: 5}
Now lets say we have an array:
var objectContainer = []
And we fill this objectContainer with x number of myobj
Now we wish to find the myobj that has the id value set to 30
You could use a loop but in worst case you would have to loop through the whole array before finding your value.
So my question is does JaVaScript have a function for these situations or does AngularJsprovide additional helpers to solve this?
You have a lot of different solutions :
Javascript FIND : https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find
Example :
var myobject = objectContainer.find(function(value){ return value.id === 1; });
Angular filter : https://docs.angularjs.org/api/ng/filter/filter
If your ids are unique you could also use a map instead of an array :
Exemple :
var myobj = {id: 1, text: 'hello world', user_id: 5};
var objectContainer = {};
objectContainer[myobj.id] = myobj;
etc
Your value of 'x' is the array indexer. So objectContainer[29] should point to the myobj in the 30th position.
Also you can use my solution of finding objects in an array.
But still it will loop over all elements of an array.

Underscore.js - without and difference methods trouble

I am trying to use the _.without and _.difference methods in the underscore.js library with no luck.
Here is some code.
var someIds = _.pluck(parsedID1, 'id');
var otherIds = _.pluck(parsedID2, 'id);
Here is where the trouble starts, I want to remove all of the otherIds out of the someId's list. So I have two options according to the website, either I can use _.difference || _.without. I use them like so...
var newArray = _.without(_.toArray(someIds), _.toArray(otherIds));
I have also tried to do this with _.difference as well, but I cant seem to get the methods to do anything other than return a copy of the first argument into the function. I have also tried passing the arguments into the functions without using the _.toArray() but the same thing happens.Has anyone ever encountered this error before?
EDIT:
I have tried the way as proposed below. I will give some more code in hopes of fixing this.
The arrays that I am passing in as arguments are in the following format.
var array = ['100004191488120', '100004191488321'];
When I pass into the _.difference I do as follows:
var newArray = _.difference(someIds, otherIds);
If someIds length is 657 and otherIds is 57 I should be getting a result of 600 Id's. Instead I get a result of whatever the length of the first argument is, being 657.
EDIT 2: Solved
I figured out what the problem was, after all that frustration the problem lied with the second argument to difference I was passing in.
I was doing a db query and getting back a list that looked like the following.
[{ _id: 514721152222111116666777, facebook: { id: '123456789' } },
{ _id: 514721152222111116666778, facebook: { id: '12345678' } },]
After I received those results I wanted to get the facebook id so I did the following,
var array = _.pluck(users, 'facebook.id');
Thats were the problem was, that pluck was sending me back a list of undefined. Instead I had to do 2 plucks before instead of one, like the following.
var temp = _.pluck(users, 'facebook');
var arrayId = _.pluck(temp, 'id');
Thanks #ZenMaster for dropping the knowledge on the difference between _.without && _.difference. Your answer was correct, was pretty brain-dead after a binder and didn't see the obvious.
You don't need an _.toArray on the first argument of the without function
The second (and more) arguments to the without is not an array - it's a "list" of values.
The proper call would be:
var newArray = _.without(['1', '2', '3'], '1', '3');
which would result in:
['2']
In your case, you'd have to use _.difference as can be seen on JSFiddle here.
Here is the code:
var parsedID1 = [{id: '1', name: 'name1'}, {id: '2', name: 'name2'}];
var parsedID2 = [{id: '1', name: 'name1'}, {id: '3', name: 'name3'}];
var someIds = _.pluck(parsedID1, 'id');
var otherIds = _.pluck(parsedID2, 'id');
console.log(someIds, otherIds);
var newArray = _.difference(someIds, otherIds);
console.log(newArray);

Working with Java Script and multidimensional arrays

I am currently working on a website type project and I am new to JavaScript. So I have been having troubles with some parts of the syntax. Basically I am trying to print the 'id' and 'value' in the nested array arr.
var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})};
var obj = myArray[0];
document.write(obj.id);
this will print the id 1 but im not sure how to access id 10.
Also if there is an easier way to do this let me know please!
Firstly, don't use the new Array constructor. Just define an array literal [...]. So your myArray will look like:
var myArray = [{id:'1', value:'een', arr: [{id:'10', value:'een'}]}];
To get to the id of 10, you need to access myArray[0].arr[0].id;.
Proper reference would be:
obj.arr[0].id
PS: google chrome developer console is a goot playground for testing javascript object dereefrecing
You can't without iterating over the array.
If order does not matter, use an object instead:
var myObject = {
1: {id:'1', value:'een'},
10: {id:'10', value:'een'}
};
var obj = myArray[10];
document.write(obj.id);
In case the nesting in your array is intended, here's what you want:
var obj = myArray[0].arr[0];
Demo:
> var myArray = new Array({id:'1', value:'een', arr: new Array({id:'10', value:'een'})});
> myArray[0].arr[0]
{ id: '10', value: 'een' }
I would for get arrays why not create your own object ?
http://www.w3schools.com/js/js_objects.asp

Javascript defining array. "arrayception"

I am trying to create a list of "items" in a canvas game. For example, an array named list. Each element must contain the information about each item. First element will contain something different. I will remove first one with 'shift()' command. Like :
list.shift();
list[0]['name']
list[0]['id']
list[0]['x']
list[0]['y']
list[1]['name']
list[1]['id']
list[1]['x']
list[1]['y']
but i don't know how to define something like this. normally i define arrays like
{"name" : xx, "id" : 5 ... }
but this works like :
list['name']
list['id']
use:
var list = [];
list[0] = {name: 'xx', id: 0, /*etc*/};
list[1] = {name: 'yy', id: 1, /*etc*/};
it creates an array of objects. You can use it like this:
var first = list.shift();
first.name; //=> xx
//or
var first = list[0];
first.name; //=> xx
Note: using {...} (Object literal) creates an Object, not an Array. An array can be created using an Array literal: [...]. Although an object is sometimes said to be an Associative Array, it is not an Array object, so things like {...}.shift() will not work for Objects.
There are no associative arrays in javascript.
so for instance , when you do
var _array = []
_array["field1"] ="value";
you are actually adding a property to the _array object .
_array.field1 = value <=> _array["field1"] ="value";
so if you want to create a collection of objects , do
var collection =[];
var myObject = {"field1":"value1"};
collection.push(myObject);

Javascript, jquery - Call array position by using a variable name

I have 2 arrays:
var array1 = [50,60];
var array2 = [120,180];
I am passing a value to a variable like this:
var curId = $(this).attr('id');
I want to set the content of #result to a computation like this:
$(#result).text(number * curId[0]);
Number is a variable predefined by me, and curId[0] shoul actually translate to array1[0] or array2[0], depending on the css class.
Can anyone tell me the right syntax for this? I'm pretty noob at js.
Thanks.
You can use a variable to hold the array that you want to use:
var myArray;
if (something)
myArray = array1;
else
myArray = array2;
$('#result').text(number * myArray[0]);
If you're trying to get the array in a variable from a string containing the name of the variable, you should use an object, like this:
var arrays = {
array1: [50,60],
array2: [120,180]
};
var myArray = arrays[curId];
$('#result').text(number * myArray[0]);
So curId will be the string "array1" or "array2"? Then you'd do it like this:
var lookups = {
array1: [50, 60],
array2: [120,180]
};
var curId = $(this).attr('id');
$('#result').text(number * lookups[curId[0]]);
What that does is create an object (lookups) to contain this information you're looking up. That object has the properties array1 and array1, which are your arrays. You get the string "array1" or "array2" from the ID of your element into the variable curId, and then you use the fact that Javascript lets you look up properties by their name using [] syntax. All of these are the same:
a = lookups.array1;
// is the same as
a = lookups["array1"];
// is the same as
a = lookups["array" + "1"];
// is the same as
s = "array1";
a = lookups[s];
Technically, if your arrays are declared at global scope, you could do that without using the lookups object, but if you're fairly new to Javascript I won't go into why, and regardless, I'd recommend using one.

Categories

Resources