So i have 2 single dim arrays
array1 = [1,2,3];
array2 = [4,5,6];
And an empty 2-dim array
setArray = [[],[]];
How am i going to push the contents of the arrays to setArray so that it looks like this... considering we don't know the length of the single dim arrays?
setArray = [
[1,2,3],
[4,5,6]
];
I'm working on a project and my problem looks like this. Thank you.
if you just want to push contents of the two arrays in setArray you can do something like this:
Each element of setArray will have a reference to one of the arrays.
var array1 = [1,2,3], array2 = [4,5,6];
var setArray = [];
setArray.push(array1);
setArray.push(array2);
console.log(setArray);
array1 = [1,2,3]; array2 = [4,5,6];
setArray = [array1,array2];
console.log(setArray)
You can do it this way too.
Related
Has any vuejs veteran experience this on VueJS(v2) where you have 2 arrays on a Component, and you push a value to the 1st array and the 2nd array gets the value also WITHOUT TOUCHING IT.
This is the first time I've encountered this, fyi I've been using VueJS for more than 2yrs already.
Additional information I have a VERY VERY similar component with exactly the same data variables and it doesn't happen, only on the 2nd Component.
array1 = [];
array2 = [];
array1.push('gether');
output should be
array1 = ['gether'];
array2 = [];
WHAT ACTUALLY HAPPENS
array1 = ['gether'];
array2 = ['gether'];
I've also played with the Google DevTools Vue Debugger.
Adding an entry on the array1 ONLY also adds the value on the array2.
kinda mind boggling
Because arrays in JS are reference values, so when you try to copy it using the = it will only copy the reference to the original array and not the value of the array. To create a real copy of an array, you need to copy over the value of the array under a new value variable. That way this new array does not reference to the old array address in memory.
To achieve this you can use array.slice() method as it creates a new array not a mere reference !
See Example and understand difference =>
Using reference (=)
let array = ["some text"]
// Making it equal to main array and using reference to copy
array1 = array;
array2 = array;
array1.push('gether');
console.log(array2)
Using array.slice() to clone
let array = ["some text"]
// Making it equal to main array and using slice to copy
array1 = array.slice();
array2 = array.slice();
array1.push('gether');
console.log(array2)
When you make two arrays equal to the same value, you make them equal by reference.
So
foo = ['a', 'b', 'z']
array1 = foo;
array2 = foo;
array1.push('d');
console.log(array2) //Outputs: ['a', 'b', 'c', 'd']
Is expected behaviour.
However that is not the same as the given example in your question. Run snippet below to see the difference.
To avoid this, you can use slice() to create a copy of the original array. I added an example to the code snippet.
let foo = ["a", "b"];
let array1 = foo;
let array2 = foo;
array2.push("c");
console.log(foo); // Outputs ["a", "b", "c"]
console.log(array1); // Outputs ["a", "b", "c"]
let array3 = [];
let array4 = [];
array4.push("a");
console.log(array3); // Outputs []
console.log(array4); // Outputs ["a"]
let bar = ["a", "b"];
let array5 = bar.slice();
bar.push("c");
console.log(bar); // Outputs ["a", "b", "c"]
console.log(array5); // Outputs ["a", "b"]
Here is the array of objects that is to be push to an array
[{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}]
How to achieve this array below from the above
"array": [
[
[
11,
21
],
[
31,
41
],
[
10,
20
],
[
11, //first object again
21
]
]
]
Used array map to push elements but couldn't figure out a way to push the first object again
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
You can do this,
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
array1.push(array1[0])
var array2 = [array1.map(item=>[item.a, item.b])];
console.log(array2);
You just add another line of code that inserts that first index.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
array2[0].push([array1[0].a, array1[0].b]);
console.log(array2);
Do you need the double array on the outside though?
Anyway, another way would be to just copy the first array you originally pushed.
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(item=>[item.a, item.b])];
array2[0].push(array2[0][0].slice());
console.log(array2);
And you can also make your .map() a little different using Object.values:
var array1 = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
var array2 = [array1.map(Object.values)];
array2[0].push(array2[0][0].slice());
console.log(array2);
This can be done my manually pushing the first element again after you've done the mapping.
The unshift() method can be used to push to the front of array.
var array2 = [array1.map(item=>[item.a, item.b])];
array2.unshift([array1[0].a, array1[0].b])
I agree with slappy's answer, but no need to apply slice
const arr = [{"a":11,"b":21},{"a":31,"b":41},{"a":10,"b":20}];
const arr2 = [arr.map(item=>[item.a, item.b])];
arr2.push(arr2[0][0]);
How come console shows "potato" instead of "JAN" when you console out arr2?
arr1[0]='Potato' is done after the line 4, so why arr2 is not equal to initial arr1? (array at line 1)
Both variables have an instance of the same array.
If you want to avoid that, make something like this instead const arr2 = [...arr1]. That will create new array with same elements as the first one.
You have to make new array from variable 1
Just try:
let arr2 = Array.from(arr1)
You can use const arr2 = [...arr1]; to immutable array clone
var arr1 = ['JAN', 'FEB'];
const arr2 = [...arr1];
arr1[0] = 'Potato';
console.log(arr2)
`
This question already has answers here:
How to insert an item into an array at a specific index (JavaScript)
(28 answers)
Closed 6 years ago.
i have a situation like this,
i have 2 array1 as array1 = ["fruit","vegetables"];
and
array2 = [["apple","banana"],["tomato"]]; // index 0:represent fruit i,e (["apple","banana"]), index 1: vegetables i,e (["tomato"])
my question : how can i push item from array1 so as to make my array2 look like this
[["fruit","apple","banana"],["vegetables","tomato"]];
with that i can determine index:0 as category.
MY data structure is these 2 array array1 = ["fruit","vegetables"]; AND array2 = [["apple","banana"],["tomato"]];
if i'm able to get key value pair array that would good for me.
my sample data:
array1 = ["fruit","vegetables"];
array2 = [["apple","banana"],["tomato"]]; //expected output :[["fruit","apple","banana"],["vegetables","tomato"]];
Use Array#unshift method.
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
var array3 = array2.map(function(v, i) { // iterate over the array to generate the new array
var arr = v.slice(); // copy the array
arr.unshift(array1[i]) // insert element at beginning
return arr; /// return generated array
});
console.log(array3)
UPDATE : If you don't want to create a new array then you can avoid the copying part.
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
array2.forEach(function(v, i) { // iterate over the array
v.unshift(array1[i]) // insert element at beginning
});
console.log(array2)
With ES6 arrow function :
var array1 = ["fruit", "vegetables"],
array2 = [
["apple", "banana"],
["tomato"]
];
array2.forEach((v, i) => v.unshift(array1[i]));
console.log(array2)
Try this Array.map() and Array.unshift() .unshift() push the data into array [0]index position.
array1 = ["fruit","vegetables"];
array2 = [["apple","banana"],["tomato"]];
array2.map((a,i) => a.unshift(array1[i]))
console.log(array2)
function myFunction()
{
var Arr2
if(Arr1!=null)
{
Arr2=Arr1
console.log("Arr2 before for: "+Arr2)
console.log("Arr1 before for: "+Arr1)
}
for(var index=-1+Arr2.length;index>=0;index--)
{
if(Arr2[index]=="to_delete")
{
Arr2.splice(index,1)
}
}
console.log("Arr1 after for: "+Arr1)
console.log("Arr2 after for: "+Arr2)
}
I create Arr2 in a function, Arr2=Arr1, the problem is that Arr1 is also being spliced during for, and from these last two console.logs i am informed that these 2 arrays are the same. (I only want to change Arr2)
When you do Arr2 = Arr1, you're just copying the reference to that array, you're not making a copy of the array itself. So both Arr1 and Arr2 will now refer to the same array.
Try changing
Arr2=Arr1
to
Arr2 = Arr1.slice()
which should copy all of the elements in Arr1 to the new Arr2. Check out Array.prototype.slice for more info.
You could just use filter Array method like this :
var arr2 = arr1.filter(x => x!="to_delete");
You are creating a reference to Arr1, not a new object.
Think of it this way:
Think of it this way: when you initialise Arr1, you're allocating it to a piece of memory on the heap. This reference is then given an address.
The assignment var Arr2 = Arr1 equals the same as saying, Arr2 is the same as Arr1 by reference. Which means it points to the same memory address.
If you want to make a copy of an object, a.k.a. pass it by value, you should use one of the following methods.
var Arr2 = Arr1.slice(0);
Keep in mind however that if your array contains objects, these are cloned by reference with this method. Example:
var Arr1 = [{a: 1, b: 2, c:3}, {d: 4, e: 5, f: 6}]
var Arr2 = Arr1.slice(0)
Arr1[0].a = 2;
console.log(Arr2[0].a) // this will output 2
If you want to easily do a deep clone without having to write the code to pass the object references by value, you can use something like lodash or just:
var Arr2 = JSON.parse(JSON.stringify(Arr1));
Which also works.