Generating an array with sub-arrays - javascript

I realize this is a somewhat off manner of operations, but for the sake of possibility, I'm wondering if anyone can help?
Here array2 is holding the end state I would like array1 to hold (only I want to do it with the for loop. It's fine that each sub_array's have to be initialized as their own variables, I'm just trying to get the array1 to hold N number of sub_arrays via the loop.
Here is the example I've tried, but trying to "compile" it via a string doesn't allow the sub_arrays to be called in a useable manner.
var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []
var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]
for (var i = 0; i < numberOfSubArrays; i++) {
array1[i] = "sub_array" + i
}
Any thoughts would be much appreciated!

var numberOfSubArrays = 3
var sub_array1 = [1]
var sub_array2 = [2]
var sub_array3 = [3]
var array1 = []
// we don't need array2 at all
//var array2 = [sub_array1,sub_array2,sub_array3]
// you need to count from 1..n, as you named your sub_arrays like that
for (var i = 1; i <= numberOfSubArrays; i++) {
// you can use eval, but be careful, eval is evil!
array1[i-1] = eval("sub_array" + i)
}
console.log(array1);

Using eval is yucky. This will work in browsers:
var numberOfSubArrays = 3
var sub_array1 = []
var sub_array2 = []
var sub_array3 = []
var array1 = []
var array2 = [sub_array1,sub_array2,sub_array3]
for (var i = 0; i < numberOfSubArrays; i++) {
array1[i] = window["sub_array" + i + 1];
}
In browsers, "global" vars are really objects in "window".
Note: this will not work in tools like jsfiddle, because they put your code inside a function (that you don't see).

Related

How to generate an array of words (e.g. value_1, value_2,..., value_#) where the number of words is equal to #?

I have a variable (for example):
var numINeed = 4
I need to dynamically create an array like so:
var arrayINeed = ["value_1","value_2","value_3","value_4"]
Where the last item is formatted such that the # in value_# is equal to var numINeed, meaning that the length of arrayINeed = length of var numINeed
Attempted so far:
I've attempted to create the array using a for loop (I'm using Vue JS by the way)
data: () => ({
arrayINeed: [],
variableA: []
}),
for (var i = 0; i<this.numINeed; ++i) {
this.variableA = "value_" + i;
this.arrayINeed.push(this.variableA);
}
I believe this might be written wrongly. How might I be able to make it work as intended?
using ES6:
let arrayINeed = Array.from(Array(4), (_,x) => "value_" + (x+1));
console.log(arrayINeed);
I just edited your code. Variable i is starting from zero, So I added one to it.
var numINeed = 4;
arrayINeed = [];
for (var i = 0; i<numINeed; ++i) {
let variableA = "value_" + (i+1);
arrayINeed.push(variableA);
}
console.log(arrayINeed);
A short code could be this:
var numINeed = 4;
var newArray = Array(numINeed).fill('').map((v, i) => `value_${i+1}`);
console.log(newArray);
Generate array using while loop
var numINeed = 4;
var arrayINeed = [];
var i = 1;
while (i < numINeed + 1) {
arrayINeed.push("value_" + i);
i++;
}
console.log(arrayINeed);

How can I push all array variables of N arrays in just one array over an loop function?

I have an problem to figure out how to write code in JavaScript for that:
i have many arrays -> 1 to N arrays like that
let array_0 = ["a","b","f"];
let array_1 = ["c","b","g","r"];
let array_2 = ["a","b","f","2","43"];
..to N..
let array_N = ["a","a","s","d"];
at next i need all the variables in just one array like that:
let array_fin = ["a","b","f","c","b","g","r","a","b","f","2","43","a","a","s","d"];
or over the console.log() -> 0: ["a","b","f","c","b","g","r","a","b","f","2","43","a","a","s","d"];
but over an loop function for all array_N's
I tried to do that over the map() function, but the map function gives me an array like that:
0: ["a","b","f"]
1: ["c","b","g","r"]
2: ["a","b","f","2","43"]
..
N
but that's not what I need and I couldn't figure out which command could do that.
I tried also an function like push(), but I could not figure out how to call that over an loop function to handle N array's.
If you don't want to type them all out, just make them global variables using var and join them using spread syntax ...array_N and a while-loop:
var array_0 = ["a","b","f"];
var array_1 = ["c","b","g","r"];
var array_2 = ["a","b","f","2","43"];
var array_3 = ["a","a","s","d"];
let result_array = [];
let i = -1;
while (window[`array_${++i}`] instanceof Array) {
result_array = [...result_array, ...window[`array_${i}`]];
}
console.log(result_array);
And yes, this will work for 1500+ Arrays, too :)
Just use concat() to merge all your arrays like this:
let array_0 = ["a","b","f"];
let array_1 = ["c","b","g","r"];
let array_2 = ["a","b","f","2","43"];
let array_N = ["a","a","s","d"];
let array_fin = array_0.concat(array_1, array_2, array_N);
console.log(array_fin);
Solution using Array#filter and eval. Not recommend to be used, since eval has security issues. Just for knowledge that this is also possible.
let array_0 = ["a","b","f"];
let array_1 = ["c","b","g","r"];
let array_2 = ["a","b","f","2","43"];
const res = [];
for(let i = 0;;i++){
try {
const arr = eval(`array_${i}`);
res.push(...arr.filter(a=>!res.includes(a)));
} catch(e){
console.log(e.message);
break;
}
}
console.log(res);
Why not to use eval
You can access the window object in order to access global variables (i.e the arrays) and make a loop for concatenate they, as shown on next example:
var array_0 = ["a","b","f"];
var array_1 = ["c","b","g","r"];
var array_2 = ["a","b","f","2","43"];
var array_3 = ["a","a","s","d"];
// Create the array of all arrays.
let numOfArrays = 4;
var array_all = [];
for (i = 0; i < numOfArrays; i++)
{
array_all = array_all.concat(window['array_' + i]);
}
console.log(array_all);

How to extract values from an array of arrays in Javascript?

I have a variable as follows:
var dataset = {
"towns": [
["Aladağ", "Adana", [35.4,37.5], [0]],
["Ceyhan", "Adana", [35.8,37], [0]],
["Feke", "Adana", [35.9,37.8], [0]]
]
};
The variable has a lot of town data in it. How can I extract the first elements of the third ones from the data efficiently? I,e, what will ... be below?
var myArray = ...
//myArray == [35.4,35.8,35.9] for the given data
And what to do if I want to store both values in the array? That is
var myArray = ...
//myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]] for the given data
I'm very new to Javascript. I hope there's a way without using for loops.
On newer browsers, you can use map, or forEach which would avoid using a for loop.
var myArray = dataset.towns.map(function(town){
return town[2];
});
// myArray == [[35.4,37.5], [35.8,37], [35.9,37.8]]
But for loops are more compatible.
var myArray = [];
for(var i = 0, len = dataset.towns.length; i < len; i++){
myArray.push(dataset.towns[i][2];
}
Impossible without loops:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2][0]);
}
// at this stage myArray = [35.4, 35.8, 35.9]
And what to do if I want to store both values in the array?
Similar, you just add the entire array, not only the first element:
var myArray = [];
for (var i = 0; i < dataset.towns.length; i++) {
myArray.push(dataset.towns[i][2]);
}
// at this stage myArray = [[35.4,37.5], [35.8,37], [35.9,37.8]]

How to combine these two JavaScript arrays

I have two JavaScript arrays below that both have the same number of entries, but that number can vary.
[{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}]
[{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}]
I want to combine these two arrays so that I get
[{"5006":"GrooveToyota"},{"5007":"GrooveSubaru"},{"5008":"GrooveFord"}]
I'm not sure how to put it into words but hopefully someone understands. I would like to do this with two arrays of arbitrary length (both the same length though).
Any tips appreciated.
It's kind of a zip:
function zip(a, b) {
var len = Math.min(a.length, b.length),
zipped = [],
i, obj;
for (i = 0; i < len; i++) {
obj= {};
obj[a[i].branchids] = b[i].branchnames;
zipped.push(obj);
}
return zipped;
}
Example (uses console.log ie users)
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var combined = [];
for (var i = 0; i < ids.length; i++) {
var combinedObject = {};
combinedObject[ids[i].branchids] = names[i].branchnames;
combined.push(combinedObject);
}
combined; // [{"5006":"GrooveToyota"},{"5006":"GrooveSubaru"},{"5006":"GrooveFord"}]
Personally, I would do it IAbstractDownvoteFactor's way (+1), but for another option, I present the following for your coding pleasure:
var a = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}];
var b = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}];
var zipped = a.map(function(o,i){ var n={};n[o.branchids]=b[i].branchnames;return n;});
similar to #robert solution but using Array.prototype.map
var ids = [{"branchids":"5006"},{"branchids":"5007"},{"branchids":"5009"}],
names = [{"branchnames":"GrooveToyota"},{"branchnames":"GrooveSubaru"},{"branchnames":"GrooveFord"}],
merged = ids.map(function (o, i) { var obj = {}; obj[o.branchids]=names[i].branchnames; return obj; });
merged; //[{5006: "GrooveToyota"}, {5006: "GrooveSubaru"}, {5006:"GrooveFord"}]
Cheers!

How do I divide a complex string into 3 seperate arrays?

Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values
mystring = 4|black|cat, 7|red|dog, 12|blue|fish
Here's where I want to be:
I want to end up with three arrays.
array1=("4","7","12")
array2=("black","red","blue")
array3=("cat","dog","fish")
I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.
I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:
var arr1 = [], arr2 = [], arr3 = [],
mystring = "4|black|cat, 7|red|dog, 12|blue|fish";
mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) {
arr1.push($1);
arr2.push($2);
arr3.push($3);
});
Example
You want to use the split() method :
var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]
//etc...
Like this?:
var values = mystring.split(',');
var arrays = new Array();
for(var i=0; i < values.length; i++) {
var parts = values[i].split('|');
for(var j = 0; j < parts.length;j++) {
if(!arrays[j]) {
arrays[j] = new Array();
}
arrays[j].push(parts[j]);
}
}
Will give you an array that contains those three arrays.
var str = '4|black|cat, 7|red|dog, 12|blue|fish';
var tmp = str.split(',');
var firstArray = Array();
var secondArray = Array();
var thirdArray = Array();
for( var i in tmp ){
var splitted = tmp[i].split('|');
//alert(true);
firstArray[i]=splitted[0];
secondArray[i]=splitted[1];
thirdArray[i]=splitted[2];
}

Categories

Resources