I have one array in javascript like
var arr = ["aa","bb","cc", "dd"];
and now I want to store these values into multiple arrays dynamically like
var arr1 = ["aa"];
var arr2 = ["bb"];
var arr3 = ["cc"];
var arr4 = ["dd"];
Here the as per the size of the "arr" array I need to create dynamic arrays to store those values. For example in "arr" I have 4 values then I need to create 4 dynamic arrays to store 4 values.
I dont have any idea how to achieve this any help?
The only way I can think of doing exactly what you are asking for is with eval. I don't suggest using it so I put together an object, which is close and preferred.
http://jsfiddle.net/P9SSA/1/
var myOneArray = ["a","b","c","d"];
var varPrefix = "arr";
var myObj = {};
for (var i = 1; i <= myOneArray.length; i++) {
eval(varPrefix + i + '=["' + myOneArray[i-1] + '"]');
myObj[varPrefix + i] = [myOneArray[i-1]];
}
document.write(arr1);
document.write("<br>");
document.write(myObj.arr3);
In global scope you can do:
arr.forEach( function( value, index ) {
window["arr"+(index+1)] = [value];
});
Inside arbitrary scope, this is only possible under non-strict eval:
var arr = ["aa","bb","cc", "dd"];
eval( arr.map( function( value,index) {
value = typeof value == "string" ? '"' + value + '"' : value;
return 'var arr'+(index+1)+' = ['+value+']';
}).join(";") + ";" );
Evaluates the following code:
var arr1 = ["aa"];
var arr2 = ["bb"];
var arr3 = ["cc"];
var arr4 = ["dd"];
forEach shim
map shim
var arrayOfArrays = [];
for (var i = 0; i < arr.length; i++) {
arrayOfArrays[i] = [];
arrayOfArrays[i].push(arr[i]);
}
Related
My goal is to have a bunch of arrays, para1, para2.... para20, and find all of the arrays with multiple elements in it, and then to be able to access them. For example I want an if statement in a for loop that would basically check all of my arrays to see which ones have multiple elements. Then, for the ones that do have multiple elements I would use an if statement to extract a particular item from each array.
var para1 = ["NB4-CAXL-14U-12-"];
var para2 = ["K"];
var para3 = ["-270°C to 1372°C, –454°F to 2501°F"];
var para4 = ['1/8"', '3/16"', '1/4"'];
var para5 = ['6"', '12"', '18"'];
for (var j = 1; j < 10; j++) {
var lenId = "para" + j;
console.log(lenId.length);
}
document.getElementById("demo").innerHTML = typeof lenId;
I defined a few arrays and made a for loop that generated a variable that was the name of each of the arrays, but when i went to check the length of the arrays i realized they are all 5, because lenId = "para1" is just a string with 5 letters in it. How would i be able to check para1 to see how many elements are in the array? Or is there a better method for checking the length of all my arrays by possibly putting them all into one larger array or something? Any help would be greatly appreciated
Put the arrays in an object:
//Initializing the object:
var O = {
para1: ["NB4-CAXL-14U-12-"],
para2: ["K"],
para3: ["-270°C to 1372°C, –454°F to 2501°F"],
para4: ['1/8"', '3/16"', '1/4"']
};
//Adding a new key to the object:
O.para5 = ['6"', '12"', '18"'];
//Getting the object's keys and their lengths:
for(var j in O) {
console.log(j + ': ' + O[j].length);
}
//Accessing an individual array element:
console.log(O.para4[1]); //3/16"
//Iterating through the object's array values using a for loop
for(var j in O) {
for(var i = 0 ; i < O[j].length ; i++) {
console.log(j + ': Element ' + i + ': Value ' + O[j][i]);
}
}
//Iterating through the object's array values using forEach
for(var j in O) {
O[j].forEach(function(val, i) {
console.log(j + ': Element ' + i + ': Value ' + val);
});
}
I would go ahead and throw your arrays into a single array. Then you can more easily do operations over that array without having to worry about numbering. The number is implicit based on the index!
var paras = [];
paras.push(["NB4-CAXL-14U-12-"]);
paras.push(["K"]);
paras.push(["-270°C to 1372°C, –454°F to 2501°F"]);
paras.push(['1/8"', '3/16"', '1/4"']);
paras.push(['6"', '12"', '18"']);
paras.forEach(function(para) {
console.log(para.length);
});
It's not pretty, but it looks like you are storing these arrays in the global scope (client-side), so technically you could refer to each variable as a property of window:
for (var j = 1; j < 10; j++) {
var lenId = "para" + j;
console.log(window[lenId].length);
}
If arrays are not dynamically generated and you define them like in your example, the better way to do that is by using standard array method filter. It accepts the function as a parameter that returns a boolean and tells whether the array item should be filtered or not. You want to use it like so:
var para1 = ['1', '2', '3'];
var para2 = ['1'];
var para3 = ['1', '2'];
var arraysToFilter = [para1, para2, para3];
var filteredArray = arraysToFilter.filter(function (paraArray) {
// returns true if array has more than one element;
return paraArray.length > 1;
});
Now filteredArray would be an array with two elements - para1 and para3
Is it possible to create the the data1 array without using nested for loops?
// My starting Normalized data
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]];
// What I want the result to look like Denormalized
var data1 = [{"name":"John", "age":20},{"name":"Tom", "age":25}];
// My solution
var data1 = [];
for(var i = 0; i < data2.length; i++){
var temp = {};
for(var y = 0; y < fields.length; y++){
temp[fields[y]] = data2[i][y];
}
data1.push(temp);
}
You can use map and forEach
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]];
var data1 = data2.map(function(arr){
var obj = {};
arr.forEach(function(val, ind){ obj[fields[ind]] = val; });
return obj;
});
but it is basically nest loops.
Or you could start getting acquainted with Javascript tools like the underscore/lodash libraries that offer a lot of utilities functions for cases like this.
For example, using _.zipObject() offered by lodash:
fields = ["name", "age"];
data2 = [["John", 20],["Tom", 25]];
res = [];
data2.forEach(function(arr) {
res.push(_.zipObject(fields, arr));
});
In essence as #epascarello mentioned, you are still doing a double loop. It's just more elegant (subject always to coding taste) and more compact.
No loops...
var data1 = [];
data1.push(eval('({"' + fields[0] + '":"' + data2[0][0] +
'","' + fields[1] + '":' + data2[0][1] + '})'));
data1.push(eval('({"' + fields[0] + '":"' + data2[1][0] +
'","' + fields[1] + '":' + data2[1][1] + '})'));
Guess it depends on your definition of efficient.
Another implementation using native map and reduce (which will be nested loops - but figured I'd throw it in as another option):
var data1 = data2.map(function(currentArray, index){
return currentArray.reduce(function(objToReturn, currentValue, index){
objToReturn[fields[index]] = currentValue;
return objToReturn;
},{});
});
I finally thought of an efficient way that doesn't use nest for loops! :)
var fields = ["name","age"];
var data2 = [["John",20],["Tom",25]];
var body = "";
for(var i = 0; i < fields.length; i++){
body = body.concat("this."+fields[i] +"=args["+i+"]; ");
}
var model = new Function("args",body);
var data1 = [];
for(var i = 0; i < data2.length; i++){
var x = new model(data2[i]);
data1.push(x);
}
I am trying to grab some values out of a sting that looks like this:
W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748
I want to make an array of all the keys and another array of all the values i.e. [W1, URML, MH…] and [0.687268668116, 0.126432054521...]
I have this snippet that does the trick, but only for the first value:
var foo = str.substring(str.indexOf(":") + 1);
Use split().
Demo here: http://jsfiddle.net/y9JNU/
var keys = [];
var values = [];
str.split(', ').forEach(function(pair) {
pair = pair.split(':');
keys.push(pair[0]);
values.push(pair[1]);
});
Without forEach() (IE < 9):
var keys = [];
var values = [];
var pairs = str.split(', ');
for (var i = 0, n = pairs.length; i < n; i++) {
var pair = pairs[i].split(':');
keys.push(pair[0]);
values.push(pair[1]);
};
This will give you the keys and values arrays
var keys = str.match(/\w+(?=:)/g),
values = str.match(/[\d.]+(?=,|$)/g);
RegExp visuals
/\w+(?=:)/g
/[\d.]+(?=,|$)/g
And another solution without using regexp
var pairs = str.split(" "),
keys = pairs.map(function(e) { return e.split(":")[0]; }),
values = pairs.map(function(e) { return e.split(":")[1]; });
JSFiddle
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275, S3:0.00869514129605, PC1:0.00616885024382, S5L:0.0058163445156, RM1L:0.00540508783268, C2L:0.00534633687797, S4L:0.00475882733094, S2L:0.00346630632748";
var all = str.split(","),
arrayOne = [],
arrayTwo = [];
for (var i = 0; i < all.length; i++) {
arrayOne.push(all[i].split(':')[0]);
arrayTwo.push(all[i].split(':')[1]);
}
parse the string to an array
var str = "W1:0.687268668116, URML:0.126432054521, MH:0.125022031608, W2:0.017801539275";
var tokens = str.split(",");
var values = tokens.map(function (d) {
var i = d.indexOf(":");
return +d.substr(i + 1);
});
var keys = tokens.map(function (d) {
var i = d.indexOf(":");
return d.substr(0, i);
});
console.log(values);
console.log(keys);
http://jsfiddle.net/mjTWX/1/ here is the demo
I have two arrays which are created from the inputs of a user like so:
var impArray = [];
$('[id^=imp]').on('change', function(){
var value = $(this).val();
var name = ($(this).attr('name').replace('imp-',''))
impArray[name] = value;
console.log(impArray);
})
var assessArray= [];
$('[id^=assess]').on('change', function(){
var value = $(this).val();
var name = ($(this).attr('name').replace('assess-',''))
assessArray[name] = value;
console.log(assessArray);
})
These create arrays like
assessAray
1-1: 10
1-2: 15
1-3: 9
impArray
1-1: 6
1-2: 14
1-3: 2
I then need to do a simple calculation with the matching keys like:
$('#comp-1-1').val(impArray['1-1'] / assessArray['1-1'] * 100);
Obviously I can't do this with every single one, so,
Question: How can I loop through the arrays and compare them based on keys then do something with their values?
Technically, you are working with JavaScript objects, not arrays. Your variable declarations should actually be:
var impArray = {};
var assessArray = {};
Once you have the correct variable declarations, you can use jQuery.each to iterate through keys (not indexes):
$.each(impArray, function(key, value){
$('#comp-'+key).val(assessArray[key]/value*100);
});
Try using $.each(), like:
$.each(impArray, function(i, v){
$('#comp-'+i).val(v/assessArray[i]*100);
});
Does this help you?
$.each(impArray, function(index, value){
var result = assessArray[index] / value * 100;
$('#comp-1-'+index).val(result);
});
If both arrays will always be the same length and have the object property at the same index, this should work:
http://jsfiddle.net/9DBuD/
assessArray = [{'1-1':'10'},{'1-2':'15'},{'1-3':'9'}];
impArray = [{'1-1':'6'},{'1-2':'14'},{'1-3':'2'}];
for(var i=0;i<assessArray.length;i++){
for(var prop in assessArray[i]){
for(var property in impArray[i]){
if(prop == property){
$('#comp-'+prop).val(impArray[i][property]/assessArray[i][prop]*100)
}
}
}
}
Edit
This modified fiddle and code should produce the same results even if the array indexes and sizes do not match:
http://jsfiddle.net/9DBuD/1/
Array.prototype.indexOfProp = function (property) {
for (var i = 0, len = this.length; i < len; i++) {
if (this[i][property]!=undefined) return i;
}
return -1;
}
assessArray = [{'1-2':'15'},{'1-3':'9'},{'1-1':'10'},{'1-4':'10'}];
impArray = [{'1-1':'6'},{'1-3':'2'},{'1-2':'14'}];
for(var i=0;i<assessArray.length;i++){
for(var prop in assessArray[i]){
var index = impArray.indexOfProp(prop)
if(index!=-1){
$('#comp-'+prop).val(impArray[index][prop]/assessArray[i][prop]*100)
}
}
}
I want to create an array like this:
s1 = [[[2011-12-02, 3],[2011-12-05,3],[5,13.1],[2011-12-07,2]]];
How to create it using a for loop? I have another array that contains the values as
2011-12-02,3,2011-12-05,3,2011-12-07,2
One of possible solutions:
var input = ['2011-12-02',3,'2011-12-05',3,'2011-12-07',2]
//or: var input = '2011-12-02,3,2011-12-05,3,2011-12-07,2'.split(",");
var output = [];
for(i = 0; i < input.length; i += 2) {
output.push([t[i], t[i + 1]])
}
If your values always come in pairs:
var str = '2011-12-02,3,2011-12-05,3,2011-12-07,2',//if you start with a string then you can split it into an array by the commas
arr = str.split(','),
len = arr.length,
out = [];
for (var i = 0; i < len; i+=2) {
out.push([[arr[i]], arr[(i + 1)]]);
}
The out variable is an array in the format you requested.
Here is a jsfiddle: http://jsfiddle.net/Hj6Eh/
var s1 = [];
for (x = 0, y = something.length; x < y; x++) {
var arr = [];
arr[0] = something[x].date;
arr[1] = something[x].otherVal;
s1.push(arr);
}
I've guessed here that the date and the other numerical value are properties of some other object, but that needn't be the case...
I think you want to create an array which holds a set of arrays.
var myArray = [];
for(var i=0; i<100;i++){
myArray.push([2011-12-02, 3]); // The values inside push should be dynamic as per your requirement
}