pushing array of string with variables to an array inside a loop - javascript

Could someone help me on below code? How do I push an array with variables?
function theBeatlesPlay(musicians, instruments) {
var array = []
var i;
var m = ms[i];
var it = its[i];
var string = "`${m}` plays `${it}`";
for (i = 0; i < 4; i++) {
array.push(string)
}
return array
}
Thanks a lot in advance!

Most of what you did should be placed inside the for loop. Like this:
function theBeatlesPlay(musicians, instruments){
var array = [];
for(var i=0; i<musicians.length; i++){
var m = musicians[i];
var it = instruments[i];
var string = `${m} plays ${it}`;
array.push(string);
}
return array;
}
Also note the syntax for the template literal: the whole string is delimited by backticks, and you should not have those double quotes.
Instead of iteration to 4, use the actual length of the array.

function theBeatlesPlay(musicians, instruments){
var array = []
var i;
for(i=0; i<4; i++){
var m = ms[i];
var it = its[i];
var string = "`${m}` plays `${it}`";
array.push(string)
}
return array
}

yes It is pseudo-code and It's actually something like this;
var ms = ["a a", "b b", "c c"];
var its = ["d d", "e e", "f f"];
function funct(ms, its){
var array = []
var i =0;
for(i=0; i<4; i++){
var m = ms[i];
var it = its[i];
var string = "${m} plays ${it}";
array.push(string)
}
return array
}

Related

Creating an array without hard-coding

I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:
var someStr = ["a","b","c","d"];
//I want to produce this outcome
a
ab
abc
abcd
b
bc
bcd
c
cd
d
I know I can get the # of possibilities for "a" only by this way:
var numCombinations = 0;
var comboString = '';
var outcome = [];
for(var i = 0; i < someStr.length; i++){
comboString += someStr[i];
outcome[i] = comboString;
numCombinations += i; //# of combinations from above
}
But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?
Hope this help.
function getComboStringListFromIdx(arr, idx){
var result = [];
var comboString = '';
for(var i=idx; i<arr.length; i++){
comboString += arr[i];
result.push(comboString);
}
return result;
}
var someStr = ['a','b','c','d'];
var outCome = [];
for(var i = 0; i<someStr.length; i++){
outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!
var someStr = ["a","b","c","d"];
for(var i = 0;i < someStr.length;i++) {
output(i);
}
function output(index) {
var str = "";
for(var j in someStr) {
if(j < index) {
continue;
}
str += someStr[j];
console.log(str);
}
}
This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.
var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
var str = arr[i];
for(var j=i;j<arr.length;j++){
if(i!==j)
str+=arr[j];
console.log(str);
}
}
https://jsfiddle.net/fmy539tj/

get key value pairs out from the string javascript

If my string looks like this
"<First key="ab" value="qwerty"/>
<First key="cd" value="asdfg"/>
<First key="ef" value="zxcvb"/>"
and I want to get data out in the format
ab:"qwerty"
cd:"asdfg"
ef:"zxcvb"
How should I write the JS ?
It would be useful to see the code you've attempted, but here's a way you could achieve it:
Use a regex to pick out the relevant parts of the string.
var regex = /key="([a-zA-Z]+)" value="([0-9a-zA-Z\-\.]+)"/;
Function to remove empty elements.
var notEmpty = function (el) { return el !== ''; };
split the string into an array on the carriage return and use reduce to build the new object by applying the regex to each array element.
var out = str.split('\n').filter(notEmpty).reduce(function(p, c) {
var match = c.match(regex);
p[match[1]] = match[2];
return p;
}, {});
OUTPUT
{
"ab": "qwerty",
"cd": "asdfg",
"ef": "zxcvb"
}
DEMO
Please, make your question more clear(What result data type would you like to get?), or try these functions:
var string = '<First key="ab" value="qwerty"/><First key="cd" value="asdfg"/><First key="ef" value="zxcvb"/>'
var ParseMyString1 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var result = [];
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currObj = {};
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
currObj[currKey] = currVal;
result.push(currObj);
};
};
console.log("ParseMyString1:");
console.log(result);
};
var ParseMyString2 = function(str){
var arr = str.split(/[</>]+/); //"
//console.log(arr);
var resultObj = {};
for (var i =0; i<arr.length; i++) {
var subStr=arr[i];
if (subStr.length!==0) {
var subArr = subStr.split(/[\s"=]+/); //"
//console.log(subArr);
var currKey = "";
var currVal = "";
for (var j =0; j<arr.length; j++) {
if (subArr[j]=="key"){
currKey = subArr[++j];
}else if (subArr[j]=="value"){
currVal = subArr[++j];
}
};
resultObj[currKey] = currVal;
};
};
console.log("ParseMyString2:");
console.log(resultObj);
};
$(document).ready(function(){
ParseMyString1(string);
ParseMyString2(string);
});
These functions return results as below (array of objects):
ParseMyString1:
[{ab:"qwerty"},{cd:"asdfg"},{ef:"zxcvb"}]
ParseMyString2:
{ab:"qwerty",cd:"asdfg",ef:"zxcvb"}
First, your string is not valid (double quotes within double quotes). You'd either need to escape the inner quotes with \" or just replace the inner quotes with single quotes.
But, assuming that your data was always going to be in the format you show, this simple code will extract the data the way you want:
var data = "<First key='ab' value='qwerty'/><First key='cd' value='asdfg'/><First key='ef' value='zxcvb'/>";
data = data.replace(/<First /g, " ").replace(/\/>/g, "").replace(/key=/g, "").replace(/value=/g, "").trim();
var ary = data.split(" ");
var iteration = "";
var result = "";
for(var i = 0; i < ary.length; i+=2){
iteration = ary[i].replace(/'/g, "") + ":" + ary[i+1].replace(/'/g, "\"");
alert(iteration);
result += " " + iteration;
}
alert("Final result: " + result);
Your input is a kind of XML. The best way is to treat it as such. We will parse it as XML, but to do so, we need to first wrap it in a root element:
var str = "<Root>" + input + "</Root>"
We parse it with
var parser = new DOMParser();
var dom = parser.parseFromString(str, "text/xml");
Get the document element (Root):
var docelt = dom.documentElement;
Now we can loop over its children and build our result, using standard DOM access interfaces like getAttribute:
var result = {};
var children = docelt.children;
for (var i = 0; i < children.length; i++) {
var child = children[i];
result[child.getAttribute('key')] = child.getAttribute('value');
}
> result
< Object {ab: "qwerty", cd: "asdfg", ef: "zxcvb"}
You can replace the above looping logic with reduce or something else as you prefer.
This approach has the advantage that it takes advantage of the built-in parser, so we don't end up making assumptions about the syntax of XML. For instance, the regexp suggested in another answer would fail if the attributes had spaces before or after the equal sign. It would fail if the values contained Unicode characters. It would fail in odd ways if the XML was malformed. And so on.

give name of a Variable from member of array

I want give name of an variable from member of an array like below ... but it show's SyntaxError: Parse error
var nemads=new Array("akhaber","mafakher");
var nemads[i] = new stocks(nemads[i],urls[i],"");
what i can do ?
Kind of, like this:
var nemads=new Array("akhaber","mafakher");
var arr = {};
for (var i = 0; i < nemads.length; ++i)
{
arr[nemads[i]] = "test" + i;
}
for (var i in arr)
{
var item = arr[i];
console.log(item);
}
console.log(arr["akhaber"]);
Output:
test0
test1
test0
you can go with eval() method also.
var arr = new Array("ab", "cd");
alert(arr[0]); //output is ab
eval("div" + arr[0] + " = new Array('12','34')"); //this created a new var named 'divab'
alert(divab); //output is 12,34

How to build an array from a string in javascript?

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

How to create an array like this in JavaScript?

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
}

Categories