Loop through two Array in JavaScript and Constructing a function - javascript

I have Two Arrays in Javascript as shown below :
Array one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
Array two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
Now Some how i need to loop through this Array and construct a function as shown
function NoisyData() {
return "" +
"Date,A\n" +
"20061001,3.0\n" +
"20061002,3.1\n" +
"20061003,3.2\n" +
"20061120,4.0\n" ;
}
Please help me as how to do this ??

How about this?
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push('3.0');
two.push('3.1');
two.push('3.2');
two.push('3.3');
function NoisyData() {
var result = "Date,A\n";
for(var i = 0; i < one.length;i++){
result += one[i] + "," + two[i] + "\n";
}
return result;
}
alert(NoisyData());

The faster way for long array is :
var one = new Array();
one.push(20061001);
one.push(20061002);
one.push(20061003);
one.push(20061120);
var two = new Array();
two.push(3.0);
two.push(3.1);
two.push(3.2);
two.push(3.3);
function NoisyData() {
var ret = [];
ret.push("Date,A");
for (var i=0;i<one.length;i++){
ret.push(one[i]+','+two[i]);
}
return ret.join('\n');
}
alert(NoisyData());

Your code can be a lot shorter. You can't type variables (like Array one) in javascript. To declare an Array most of the time an Array literal is sufficient.
If your arrays have the same length, you can use the code hereby to combine them into the string you need:
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combine = function(a1,a2){
var i = -1, len = a1.length, res = ['Date,A'];
while(++i < len){
res.push(a1[i]+','+a2[i].toPrecision(2));
}
return res.join('\n');
}(one,two);
Try it # http://jsfiddle.net/KooiInc/jdn6U/

You mean
function NoisyData() {
var txt = "Date,A\n"
for (var i=0, n=one.length;i<n;i++) {
txt += one[i]+","+two[i]+"\n"
}
return txt
}
UPDATE based on KooiInc's posts:
<script>
var one = [20061001,20061002,20061003,20061120]
, two = [3.0,3.1,3.2,3.3]
, combined = function(res,two){
var i = one.length;
while(i--){
res[i]+=','+two[i].toPrecision(2);
}
res.splice(0,0,'Date,A');
return res.join('\n')
}(one.slice(0),two);
alert(combined);
</script>
Instead of one.slice(0) one.clone() can be implemented as
Array.prototype.clone = function() { return this.slice(0); }
or just pass one itself instead if it is OK to modify the original array

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);

Generic code for Arrays

I want to create one loop that will access and push data from three arrays in JavaScript:
var tempArray1=new Array();
var tempArray2=new Array();
var tempArray3=new Array();
I tried following code:
for(var j=1; j<4; j++) {
var res = new Array();
var str = 'tempArray' + j;
res = str.split(" ");
}
but with this nothing happened.
Please help me to create generic code.
Brief
var res=[...tempArray1,...tempArray2,...tempArray3]
or more dynamic
var res=eval('[...tempArray1,...tempArray2,...tempArray3]') // since it is generic
DEMO :
var tempArray1=["I","love","JS"],tempArray2=["But","I'm"],tempArray3=["a crazy","JS","Programmer"]
function range(size){ /* for you case ,it returns : [1,2,3] */
return Array.from({length:size},(v,k)=>k+1)
}
function generate(size){
return eval('[...'+range(size).map((i)=>'tempArray'+i).join(',...')+']')
}
console.log(
generate(3)
)
var tempArray1 =[1,2,3];
var tempArray2 =[4,5];
var tempArray3 =[6];
function myConcat(){//This is the generic method
var result =[];
for (var i = 0; i < arguments.length; i++) {
result = result.concat(arguments[i]);
}
return result;
};
var conctenatedArray = myConcat(tempArray1,tempArray2,tempArray3);
console.log(conctenatedArray);
https://jsfiddle.net/8jwyzn0x/
**
OR
**
It would be good, if you wrap those array in a container object.
function myConcat(container){//This is the generic method
var result =[];
for(var i in container){
result = result.concat(container[i]);
}
return result;
};
var arrayContainer ={};
arrayContainer.tempArray1 =[1,2,3];
arrayContainer.tempArray2 =[4,5];
arrayContainer.tempArray3 =[6];
var conctenatedArray = myConcat(arrayContainer);
console.log(conctenatedArray);
https://jsfiddle.net/8jwyzn0x/1/

Push different object in an array with a for loop

I have an element structured like this:
Element ->
[{values: arrayOfObject, key:'name1'}, ... ,{values: arrayOfObjectN, key:'nameN'}]
arrayDiObject -> [Object1, Object2, ... , ObjectN] //N = number of lines in my CSV
Object1 -> {x,y}
I have to take data from a big string:
cityX#substanceX#cityY#substanceY#
I thought to make it this way, but it seems like it pushes always in the same array of objects. If I put oggetto = {values: arrayDateValue, key: key}; inside the d3.csv function, instead if I put outside the function it add me only empty objects.
Here is my code:
var final = new Array();
var oggetto;
var key;
function creaDati() {
var newdate;
var arrayDateValue = new Array();
var selString = aggiungiElemento().split("#");
//selString is an array with selString[0]: city, selString[1]: substance and so on..
var citySelected = "";
var substanceSelected = "";
for (var i = 0; i < selString.length - 1; i++) {
if (i % 2 === 0) {
citySelected = selString[i];
} else if (i % 2 !== 0) {
substanceSelected = selString[i];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/" + citySelected + ".csv", function(error, dataset) {
dataset.forEach(function(d) {
arrayDateValue.push({
x: d.newdate,
y: d[substanceSelected]
});
});
});
oggetto = {
values: arrayDateValue,
key: key
};
arrayDateValue = [];
final.push(oggetto);
}
}
}
Any idea ?
First you should make the if statement for the city and then for the key, which you seem to be doing wrong since you want the pair indexes to be the keys and the not pair to be the city, and you are doing the opposite. And then you need to have the d3.csv and push the objects outside of the if statement, otherwise in your case you are just adding elements with citySelected="".
Try something like :
for(var i = 0; i < selString.length -1; i+=2){
cittySelected = selString[i];
substanceSelected = selString[i+1];
key = citySelected + "#" + substanceSelected;
d3.csv("/CSV/"+citySelected+".csv", function(error, dataset){
dataset.forEach(function(d){
arrayDateValue.push({x: d.newdate, y: d[substanceSelected]});
});
});
oggetto = {values: arrayDateValue, key: key};
arrayDateValue = [];
final.push(oggetto);
}
It's is not the best way to do it, but it is clearer that what you are following, i think.
In the if(i % 2 == 0) { citySelected = ... } and else if(i % 2 !== 0) { substanceSelected = ... } citySelected and substanceSelected will never come together.
The values should be in one statement:
if(...) { citySelected = ...; substanceSelected = ...; }
The string can be splitted into pairs
city1#substance1, city2#substance2, ...
with a regex (\w{1,}#\w{1,}#).
Empty the arrayDateValue after the if-statement.
Hint:
var str = "cityX#substanceX#cityY#substanceY#";
function createArr(str) {
var obj = {};
var result = [];
var key = "";
// '', cityX#substanceX, '', cityYsubstanceY
var pairs = str.split(/(\w{1,}#\w{1,}#)/g);
for (var i = 0; i < pairs.length; i++) {
if(i % 2 !== 0) {
key = pairs[i];
// d3 stuff to create values
obj = {
// Values created with d3 placeholder
values: [{x: "x", y: "y"}],
// Pair
key: key
};
result.push(obj);
}
// Here should be values = [];
}
return result;
}
var r = createArr(str);
console.log(r);
May be you can do like this;
var str = "cityX#substanceX#cityY#substanceY",
arr = str.split("#").reduce((p,c,i,a) => i%2 === 0 ? p.concat({city:c, key:a[i+1]}) : p,[]);
console.log(JSON.stringify(arr));
RESOLVED-
The problem is about d3.csv which is a asynchronous function, it add in the array when it finish to run all the other code.
I make an XMLHttpRequest for each csv file and it works.
Hope it helps.

How to parse bracket tag on Javascript

I have tag like this, how the best way to get every key and value of those attribute and populate it within an array (number of attribute will be increasing)?
myData = '[data attr1="value1" attr2="value2" attr3="value3"]';
and get result array :
var arr = new Array();
arr['attr1'] = "value1";
arr['attr2'] = "value2";
arr['attr3'] = "value3";
and so on...
This probably does what you want, though it assumes that tag is already in the format you have described, i.e. a singular occurrence of [data ... ].
Also, the regular expression is purely based on what I've seen in your question; not sure whether it will break on other strings.
function decode(tag)
{
var r = /(\w+)="([^"]*)"/g,
h = {};
while ((m = r.exec(tag)) !== null) {
h[m[1]] = m[2];
}
return h;
}
Since you have string key in the data, use jquery object instead of array.
var arr = {};
var str = '[data attr1="value1" attr2="value2" attr3="value3"]​​​';
var n = str.split('[data ');
var str_arr = n[1].replace(']','').split(" ");
jQuery.each(str_arr,function(val){
var x = str_arr[val].split('=');
arr[x[0]] = x[1].replace('"','').slice(0,-1);
});
console.log(arr);
Try this code. It may help you.
Here is the DEMO
Though it can be more optimized if you put some more details about your code.
var tagRe = /\[(\w+)((?:\s+\w+="[^"]{0,50}")*)\s*]/g;
var attrRe = /\b(\w+)="([^"]*)"/g;
function parse(text) {
var result = [];
tagRe.lastIndex = 0; // reset start position
var tagMatch = tagRe.exec(text);
while (tagMatch) {
var currentTag = { 'name': tagMatch[1], 'attrs': {} };
var attrString = tagMatch[2];
attrRe.lastIndex = 0;
var attrMatch = attrRe.exec(attrString);
while (attrMatch) {
var attrName = attrMatch[1];
var attrValue = attrMatch[2];
currentTag.attrs[attrName] = attrValue;
attrMatch = attrRe.exec(attrString); // next match
}
result.push(currentTag);
tagMatch = tagRe.exec(text);
}
return result;
}
parse('[data attr1="value1" attr2="value2" attr3="value3"]');
> [{name:'data',attrs:{attr1:'value1',attr2:'value2',attr3:'value3'}}]
This works for any number of tags in the string. The name of the tag does not matter.

Javascript: sort objects

function Player() {
var score;
this.getScore = function() { return score; }
this.setScore = function(sc) { score = sc; }
}
function compare(playerA, playerB) {
return playerA.getScore() - playerB.getScore();
}
var players = [];
players['player1'] = new Player();
players['player2'] = new Player();
Array(players).sort(compare);
I have code that is similar to the above. When I step through the code with a debugger, the compare function never gets called and the array isn't sorted. I'm not sure what's wrong with my code?
It's not sorting because you have specified the keys that the variables within the array belong on. Sorting will only move the objects on integer-valued keys. You should see your sorting work if you create your array as follow:
var players = [new Player(), new Player()];
though, of course, it won't be very effective since you have neither a score on which to sort or a method of identifying them. This'll do it:
function Player(name, score) {
this.getName = function() { return name; }
this.getScore = function() { return score; }
this.setScore = function(sc) { score = sc; }
}
function comparePlayers(playerA, playerB) {
return playerA.getScore() - playerB.getScore();
}
var playerA = new Player('Paul', 10);
var playerB = new Player('Lucas', 5);
var playerC = new Player('William', 7);
var players = [playerA, playerB, playerC];
for (var i = 0; i < players.length; i++)
alert(players[i].getName() + ' - ' + players[i].getScore());
players.sort(comparePlayers);
for (var i = 0; i < players.length; i++)
alert(players[i].getName() + ' - ' + players[i].getScore());
Hope that helps.
The main problem lies in this line:
Array(players).sort(compare);
Array(something) makes an array with something as its element.
console.log(Array(players)); //[[player1, player2]]
Use numeric indexed array instead of using object like array as in players['player1']
Run the following code (replace console.log with alert if you don't have Firebug).
function Player() {
var score;
//return this.score - else it returns undefined
this.getScore = function() { return this.score; }
this.setScore = function(sc) { this.score = sc; }
}
function compare(playerA, playerB) {
console.log("called " + playerA.getScore() + " " + playerB.score);
//compare method should return 0 if equal, 1 if a > b and -1 if a < b
return (playerA.getScore() == playerB.getScore()) ? 0
: ((playerA.getScore() > playerB.getScore()) ? 1 : -1);
}
var players = [];
players[0] = new Player();
players[1] = new Player();
players[2] = new Player();
players[3] = new Player();
players[0].setScore(9);
players[1].score = 14;
players[2].score = 11;
players[3].score = 10;
players.sort(compare);
console.log(players);//prints sorted array
It's probably because you don't have any "array values" inside your array - textual indexes are not regarded as array values but as object propertiest (arrays are "objects in disguise" in javascript). You can add as many properties to any object but array specific methods like sort take only "real" array members as their parameteres (i.e. only with numerical indexes)
var arr = new Array()
arr[0] = 1
arr[1] = 2
arr["textual_index"] = 3
alert(arr.length);
The last line alerts "2" not "3" since there are only two values with numeric indexes.
you can also use like below:
var a = [];
a.push(obj1);
a.push(obj2);
a.sort(compare);
so you can use push method rather than an integer index

Categories

Resources