Using methods with variables in JavaScript - 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!

Related

Add array inside array in Javascript

How do I push array into a new Array.
For example
var arr = ['one','two','three'];
var newArr = [];
Now I want newArr[0] = ['one','two','three']
I have tried using push function but it pushes all the elements of arr into newArr. I want to push the entire arr as it is in newArr
var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array
You can write:
newArr[0] = ['one','two','three'];
And this will work. Or use variable:
newArr[0] = arr;
Also, array methods push or unshift will the same way in your situation work:
newArr.push(arr);
Others have answered, so I guess your question is not really clear.
As you put your question, first and only element of newArray should be the arr array, then you use
newArr.push(arr);
as Mitya and Tiij7 said.
However, maybe you meant you want to join (concat) 2 arrays in a new array? Then you would use:
var arr3 = [].concat(arr, newArr);
or
var arr3 = [...arr, ...newArr];
Or you just wanted to clone the initial array? Then use
var newArr = [...arr];

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

Match two Arrays as Object of Array

I have two arrays and I need to make it as object of array
var arr1 = [1,2,3,4,5]
var arr2 = [a,b,c]
Is there any possibility to change the array to this format[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
Could someone help me?
Try this code:
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = arr2.reduce(function(obj, item) {
obj[item] = arr1.slice(); // or = arr1 to keep the reference
return obj;
}, {});
console.log(result); // {"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
You have 2 cases:
To create clones of the array use result[item] = arr1.slice();
To keep the reference to the same array use result[item] = arr1;
Check more about the reduce() method.
I am assuming you need a object like this
{"a":[1,2,3,4,5],"b":[1,2,3,4,5],"c":[1,2,3,4,5]}
So you can do it like this.
var arr1 = [1,2,3,4,5]
var arr2 = ["a","b","c"];
var result={}
arr2.map(function(k){
result[k]=arr1;
})
console.log(result);
But here I am giving values of keys as arr1 reference so if arr1 will change value of keys in result will also change.
Is there any possibility to change the array to this
formate[a,{1,2,3,4,5}],[b,{1,2,3,4,5}],[c,{1,2,3,4,5}]
This is neither an array format nor a valid JSON literal, so this format could only be a string.
Assuming that you are looking for a string in the format you have specified
var output = "[" + arr2.map(function(value){return value+",{" + arr1.join(",") + "}"}).join("],[") + "]";
Use forEach to iterate through List and get your desired result.
var arr1 = [1,2,3,4,5];
var arr2 = ['a','b','c'];
var result = {} // Result: Object of Array
arr2.forEach(function(val, index) {
result[val] = arr1;
})
I hope this is easy to understand :)

Push datas into a multidimensional array in JS

I'm trying to push some datas into my array.
Actually my code looks like this:
arr.push('step1||item1||99');
It works but it's not the best as I need to split it after to manager datas.
How can I transform this into a multidimensional array ?
What I tried:
arr = [];
arr['step'] = 'step1';
arr['name'] = 'item1';
arr['number'] = '99';
arr.push(arr);
But it doesn't work...
Any help please.
Is there a reason you don't want these individual data points to be objects?
var arr = [];
var dataPoint = { 'step': 'step1', 'name': 'item1', 'number': 99 };
arr.push(dataPoint);
If this isn't what you're looking for, can you give a fuller explanation of what your dataset should look like so we can better understand the problem?
Array holds "indexes"
Object holds "Key" and "Value"
Array example:
var arr = new Array;
arr[0] = 'step1';
arr[1] = 'item1';
arr[2] = '99';
console.log(arr);
Object example:
var obj = new Object;
obj.stop = 'step1';
obj.item = 'item1';
obj.number = 99;
console.log(obj);
Objects in array:
var arr = new Array;
var obj = new Object;
obj.stop = 'step1';
obj.number = 99;
arr.push(obj)
console.log(arr); // Output => [{stop: 'step1', number: 99}]
maybe you mean something like this
arr=[];
var s={
step:'step1',
name:'item1',
number:'99'
}
arr.push(s);
console.log(arr);
s is an object, which works just like an array, but is referenced by a string instead of an integer:
s['step'] === 'step1'
s.step === 'step1'
arr[0] === s
Be aware that there are some differences, like you can't iterate over an object like you can an array: you need to use another method like a "for in" loop, for instance.

how to get data from an array within an array 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.

Categories

Resources