How to use array variable in array? - javascript

I have an array and I want to put same array and other array inside of the first array.
var arr=["a","b","c",arr,arr2];
var arr2=["a","b"];
var arr3=[];
arr3=arr[3];
When I print out arr, I can see
["a","b","c",,]
But if I print out arr3, The result is undefined.
How can I fix it?

You need to do this in the right order:
var arr1 = [];
var arr2 = [ "a", "b" ];
// Now arr1 and arr2 are defined so you can throw them into another array:
var arr3 = [ "a", "b", "c", arr1, arr2 ];

You've defined arr as part of itself - arr[3] is arr. But at the time, arr doesn't exist yet, so it comes out as undefined.

Related

JavaScript arrays and understanding arr[arr.length]

What is meant by arr[arr.length]. I mean what it really means or what it really does, I cannot understand the logic of how it works. Can anybody explain?
arr.length means the length of the array that spans from index 0 to arr.length - 1.
For instance if you got arr = ["a", "b", "c"], arr.length is 3.
arr[0] is "a", arr[1] is "b" and arr[2] is "c".
arr[3] does not exist, yet. but if you do arr[arr.length] = "d", you obtain ["a", "b", "c", "d"].
This is an odd construction and usually, one should simply write arr.push("d").
const arr = ["a", "b", "c"];
console.log(arr.length, arr[0], arr[1], arr[2], arr[3]);
arr[arr.length] = "d";
console.log(arr);
arr.push("e");
console.log(arr);
This statement gets the index of the last index of the array plus one. It is used to append items to an array. Equivalent to array.push().
var fruits = ["apple", "orange", "banana", "pear"];
// appends grapes to the array
fruits[fruits.length] = "grapes";
console.log(fruits);
For further reading, check out MDN's page on array methods.
arr.length is the length of the array.
arr[arr.length] is accessing by index the array length (out of bounds as length starts at 1, not index 0).
example:
const test = [1,2,3]
test[test.length]
undefined
test[test.length-1]
3
It just requests specific index of the array, Use case: Not very elegant way of adding new element to the array, like:
arr[arr.length] = newVal
arr.push(newVal)
arr = [...arr, newVal]

VueJS pushing to an array also pushes the value to another one

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"]

A way to push array of objects into an array

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 to push an element at index 0 of an array [duplicate]

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)

Merge two arrays by grouping based on elements of 1st array in Javascript

I have two arrays (arr1 & arr2) like this
var arr1 = ["A","B","C"];
var arr2 = [["A","aa"], ["A","ab"], ["A","ac"],["B","ba"],["B","bb"],["B","bc"],["C","ca"],["C","cb"]];
I want to group them together into 3rd array in javascript based on the values of first array. Desired Output:
arr3 = [ ["A",["aa","ab","ac"]], ["B",["ba","bb","bc"] ], ["C",["ca","cb"]] ]
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Please advise.
Try like this
var arr1 = ["A", "B", "C"];
var arr2 = [
["A", "aa"],
["A", "ab"],
["A", "ac"],
["B", "ba"],
["B", "bb"],
["B", "bc"],
["C", "ca"],
["C", "cb"]
];
var newVal = arr1.map(function(x) {
var filter = arr2.filter(function(y) {
return y[0] == x;
}).map(function(y) {
return y[1];
});
return [x, filter];
})
console.log(newVal);
DEMO
NOTE: I had arr2 to begin with and was able to retrieve first value and remove duplicates into arr1.
Rather than creating arr1 as a middle step, I would probably create an object as the middle step:
var obj = arr2.reduce(function(a,b){
if (!a[b[0]]) a[b[0]] = [];
a[b[0]].push(b[1]);
return a;
},{});
// obj is now {"A":["aa","ab","ac"],"B":["ba","bb","bc"],"C":["ca","cb"]}
To convert that object to your desired output array:
var arr3 = Object.keys(obj).map(function(v) { return [v, obj[v]]; });
// [["A",["aa","ab","ac"]],["B",["ba","bb","bc"]],["C",["ca","cb"]]]
If you actually need the arr1 array for something else then:
var arr1 = Object.keys(obj);
// ["A", "B", "C"]
But notice that obj is quite useful for further processing, because if you need to get the values associated with "B" you don't need to search through an array again, you can simply say obj["B"] (which will give the array ["ba","bb","bc"]). So the second "B" value is obj["B"][1].
Further reading:
.reduce()
.map()
Object.keys()

Categories

Resources