how to get data from an array within an array javascript - javascript

Let's say I have an array named derps and then I make an array inside it:
derps[0]=new Array();
how do I get/set data in the newly created array derps[0]?

Simply do this:
derps[0][0] = 'foo';
derps[0][1] = 'bar';
derps[0].push('foobar');
derps[0] = derps[0].concat([5,6,7]);
// Etc, etc.
console.log(derps[0][1]); // 'bar'
console.log(derps[0][2]); // 'foobar'
console.log(derps[0]); // ["foo", "bar", "foobar", "foobar", 5, 6, 7]
Basically, access derps[0] like you'd access any other array, because it is an array.
I'm not going to list All methods you can use on derps[0] ;-)
Also, instead of:
derps[0] = new Array();
You can use the "array literal" notation:
derps[0] = []; // Empty array, or:
derps[0] = ['foo', 'bar', 'foobar']; // <-- With data.

You can create the array with data already in it:
derps[0] = [1, 2, 3];
You can assign values to the array:
derps[0] = new Array();
derps[0][0] = 1;
derps[0][1] = 2;
derps[0][2] = 3;
You can push values to the array:
derps[0] = new Array();
derps[0].push(1);
derps[0].push(2);
derps[0].push(3);

You can push data into the new array:
derps[0].push("some data");
As an aside: you may also use an array literal to create derps[0]:
derps[0] = [];

Easy:
var derps = [];
derps.push([]);
derps[0].push('foo');
derps[0].push('bar');

If you really wish to instantiate the type of the variable before, you can proceed this way (JSFiddle).
var derps = [];
derps[0] = [];
derps[0][0] = "test";
derps[0][1] = "test2";
document.write(derps[0][1]);​
Don't forget to write var if you don't want the variable to be global.

Related

Using methods with variables in JavaScript

I have a variable:
var array = [1,2,3]
I want to reverse the array:
array.reverse()
In that example I didn't need to make a temporary variable like this:
var arrayRev = array.reverse()
or like this:
var array = array.reverse()
but some times I need to make a temporary variable with different methods.
in this example I want to join the items in the array:
var array = [1,2,3]
array.join("")
console.log(array)
The result is still [1,2,3] not 123
but if I do this:
var array = [1,2,3]
var arrayJoin = array.join("")
console.log(arrayJoin)
or this:
var array = [1,2,3]
var array = array.join("")
console.log(array)
it works!
why is that so, and how do I know whether to use this:
var array = [1,2,3]
var array = array.join("")
console.log(array)
or this:
var array = [1,2,3]
array.join("")
console.log(array)
thanks!

How to create an associative array in JavaScript literal notation

I understand that there are no associative arrays in JavaScript, only objects.
However I can create an array with string keys using bracket notation like this:
var myArray = [];
myArray['a'] = 200;
myArray['b'] = 300;
console.log(myArray); // Prints [a: 200, b: 300]
So I want to do the exact same thing without using bracket notation:
var myNewArray = [a: 200, b: 300]; // I am getting error - Unexpected token:
This does not work either:
var myNewArray = ['a': 200, 'b': 300]; // Same error. Why can I not create?
JavaScript has no associative arrays, just objects. Even JavaScript arrays are basically just objects, just with the special thing that the property names are numbers (0,1,...).
So look at your code first:
var myArray = []; // Creating a new array object
myArray['a'] = 200; // Setting the attribute a to 200
myArray['b'] = 300; // Setting the attribute b to 300
It's important to understand that myArray['a'] = 200; is identical to myArray.a = 200;!
So to start with what you want:
You can't create a JavaScript array and pass no number attributes to it in one statement.
But this is probably not what you need! Probably you just need a JavaScript object, what is basically the same as an associative array, dictionary, or map in other languages: It maps strings to values. And that can be done easily:
var myObj = {a: 200, b: 300};
But it's important to understand that this differs slightly from what you did. myObj instanceof Array will return false, because myObj is not an ancestor from Array in the prototype chain.
You can use Map:
var arr = new Map([
['key1', 'User'],
['key2', 'Guest'],
['key3', 'Admin'],
]);
var res = arr.get('key2');
console.log(res); // The value is 'Guest'
You want to use an object in this case
var myObject = {'a' : 200, 'b' : 300 };
This answer links to a more in-depth explanation: How to do associative array/hashing in JavaScript
Well, you are creating an array, which is in fact an object:
var arr = [];
arr.map;
// function(..)
arr['map'];
// function(..)
arr['a'] = 5;
console.log(arr instanceof Object); // true
You can add fields and functions to arr. It does not "insert" them into the array though (like arr.push(...)).
You can refer to an object fields with the [] syntax.
I achieved this by using objects. Your create an object, and loop through using for in loop. each x will be the index and holder[x] will be the value. an example is below.
var test = {'hello':'world','hello2':'world2'}
for(let x in holder)
{
let inxed = x;
let value = holder[x]
console.log('index ' + x + ' has value of ' + value)
}
Associate array is an array indexed with name similar to an object instead of numbers like in regular array. You can create an associative array in the following way:
var arr = new Array(); // OR var arr = [];
arr['name'] = 'david'
arr['age'] = 23;
console.log(arr['name']);
You can do what you wanted to do this way:
myNewArray = new Array ({'a' : 200, 'b' : 300})

Length property not updating on object arrays

Two problems consider the following object:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
Why does my cars array have length of 0? Do i have to update the length property manually?
Why is my stringified object empty when it has parameters in it i'm assuming it is tied into the length property?
Fiddle:https://jsfiddle.net/wcd7f8Lz/
car is initialized as an array, but used as an Object. and an object does not have length attribute...
To get the length of an object, you can do ̀̀̀̀Object.keys(obj).length (get the keys list, and because it is an array, it have a length).
But the problem is also that you initialize cars as an array, but use it as Object...
see docs here:
http://www.w3schools.com/js/js_arrays.asp
http://www.w3schools.com/js/js_objects.asp
The solution is to initialize it as Object:
//new obj
var obj = {};
obj['cars'] = {}; //And other object
obj['cars']['toyota'] = 1;
obj['cars']['mazda'] = 0;
console.log(obj);
console.log(JSON.stringify(obj));
But if you want instead a simple array:
//new obj
var obj = {};
obj['cars'] = [];
obj['cars'][1] = "toyota";
obj['cars'][0] = "mazda";
console.log(obj);
console.log(JSON.stringify(obj));
The syntax is ̀array[identifier] = value;
(and not ̀̀̀̀̀array[value] = identifier)
I've updated the fiddle.
obj.cars.length is 0, because you don't push new items in array, but change it properties:
var obj = {};
obj.cars = []; // obj.cars is empty array
obj.cars.toyota = 1; // obj.cars is empty array with a new property toyota
obj.cars.push('mazda'); // obj.cars is array with a new property toyota and one element mazda
console.log(obj.cars instanceof Array,
obj.cars.length,
Object.keys(obj.cars)); // output: true 1 ["toyota"]
Why you don't use it in this way?
var cars = [];
cars.push({name:'toyota', value:1});
cars.push({name:'mazda', value:0})
That's because you aren't using an array (despite declaring it with an array literal), you're using it as an object.
Arrays are just a special case of object, meaning they can have individual properties. These properties don't exist "in" the array but instead are properties "of" the array.
var arr = [1, 2, 3];
arr.thing = 'a';
console.log(arr.length); // 3
To add elements to an array, you should use push:
var arr = []; // length: 0
arr.push(1); // length: 1
If you want to be able to access an object both by name and index then you can combine push with custom properties.
var arr = [];
arr.push(0);
arr.mazda = 0;

Use an object-literal as array item

I have an object-literal like this
var data = {name:'racheal', class:'jss2', town:'kaduna'}
I would love this to be in an array like this
[{name:'racheal', class:'jss2', town:'kaduna'}]
You can just create an array with it:
var obj = {name:'racheal', class:'jss2', town:'kaduna'}
var arr = [obj];
Simple use of the push method on an array will achieve this:
var myObj = {name:'racheal', class:'jss2', town:'kaduna'};
var myArray = [];
myArray.push(myObj);
Or, as Tushar says in comments, you can simply initialise a new array with the Object in it:
var myObj = {name:'racheal', class:'jss2', town:'kaduna'};
var myArray = [myObj];
You can read a bit more on Arrays and their various methods and how to use them here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

javascript: get end key value?

how do i get the end key value for a javascript array?
i want to compare it with another value.
EDIT: and how do you declare a value directly with a declaration of an array. i have to use 2 lines for it.
var arrayname = new Array();
arrayname[] = 'value';
could one do that in one line?
You can create arrays in one of many ways.
var foo = new Array();
foo[0] = 'a';
foo[1] = 'b';
foo[2] = 'c';
//is the same as:
var foo = new Array();
foo.push('a');
foo.push('b');
foo.push('c');
//is the same as:
var foo = [];
foo.push('a');
foo[1] = 'b';
foo[foo.length] = 'c';
//is the same as:
var foo = ['a','b','c'];
//is the same as:
var foo = 'a|b|c'.split('|');
Of course, if you only want to build an array to pass the array to another function, you can build it anonymously on the fly:
doSomething('param1', ['a','b','c'], 'param3');
You can initialize an array at one go using:
var arrayname = [ 'value' ];
Accessing the last value uses:
arrayname[arrayname.length-1];
The previous assumes that the array has a length greater than zero. If the array can be empty you should check that length is greater than zero before trying to access the last element.

Categories

Resources