Creating an array without hard-coding - javascript

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/

Related

a code which reverses null terminated string

I am new to js.
I am trying to write a code which reverses null terminated string.
I tried writing using push and pop.
but i am not getting output, can you tell me what is the problem.
providing code below
var word = "Cell0";
//var char = word.stringCharAT();
for (i=0; i< word.length; i++) {
var pushWord = [];
pushWord.push(word[i]);
for (j=0; j< pushWord.length; j++) {
var reverseWord= [];
reverseWord = pushWord[j].pop;
console.log("reverseWord" + reverseWord);
}
}
Here's a solution.
var word = "Cell0";
var reversed = '';
for (var i = word.length-1; i >= 0; i--) {
reversed += word[i];
}
console.log(reversed);
This loops through the characters of the string in reverse and adds the characters to a new string.
pushWord[j] is not an array, .pop is not called.
Define pushWord and reverseWord arrays outside of for loop, within loop, after word[i] is pushed to pushWord, call .unshift() on reverseWord with pushWord[pushWord.length -1] as parameter.
var word = "Cell0";
var pushWord = [];
var reverseWord = [];
for (let i = 0; i < word.length; i++) {
pushWord.push(word[i]);
reverseWord.unshift(pushWord[pushWord.length - 1]);
}
console.log("reverseWord" + reverseWord);
var originalWord = "Cell0";
var reverseWord = [];
for (let i = 0; i < originalWord.length; i++) {
reverseWord.unshift(originalWord [i]);
}
console.log(reverseWord.join(''));
You don't even need to push.
Another way to achieve the result!

Alternately Join 2 strings - Javascript

I have 2 strings and I need to construct the below result (could be JSON):
indexLine: "id,first,last,email\n"
dataLine: "555,John,Doe,jd#gmail.com"
Result: "id:555,first:john,....;
What would be the fastest way of joining alternately those 2 strings?
I wrote this - but it seems too straight forward:
function convertToObject(indexLine, dataLine) {
var obj = {};
var result = "";
for (var j = 0; j < dataLine.length; j++) {
obj[indexLine[j]] = dataLine[j]; /// add property to object
}
return JSON.stringify(obj); //-> String format;
}
Thanks.
var indexLine = "id,first,last,email";
var dataLine = "555,John,Doe,jd#gmail.com";
var indexes = indexLine.split(',');
var data = dataLine.split(',');
var result = [];
indexes.forEach(function (index, i) {
result.push(index + ':' + data[i]);
});
console.log(result.join(',')); // Outputs: id:555,first:John,last:Doe,email:jd#gmail.com
If you might have more than one instance of your object to create, you could use this code.
var newarray = [],
thing;
for(var y = 0; y < rows.length; y++){
thing = {};
for(var i = 0; i < columns.length; i++){
thing[columns[i]] = rows[y][i];
}
newarray.push(thing)
}
source

How to access a variable outside of a nested for loop in JavaScript

I have a JS function with for loops. Inside the nested for loops, str element prints all of the intended elements. But, outside it doesn't print all of it. I would appreciate any help. Here is my code:
function getResearchersFullName(allDataJson){
var str = [];
var myarr = [];
var c = 0;
for(var i = 0; i < allDataJson.length; i++){
myarr[i] = allDataJson[i].Researchers.split(", ");
for(var j = 0; j < myarr[i].length; j++){
str[c] = myarr[i][j];
//console.log(str[c]); //prints as expected
}
}
return str;
}
I am trying to use the returned value as follows but it only prints one of the str values.
var fullnames = getResearchersFullName(allDataJson);
for(var i = 0; i <fullnames.length; i++){
console.log(fullnames[i]); //returns only 1 object
}
Your code never increments c. The only element of str that's ever modified is element 0.
Use str.push(myarr[i][j]); and you won't need c at all.

Converting Object to sequential array format - javascript?

I am having following object structure
var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
Expected output is:
result = [["direct","indirect"],["indirect","dir"],["dir","indir"]];
What I have tried:
var result = [];
var array = [];
for(var key in obj){
if(array.length <2) {
array.push(obj[key]);
}else{
array =[];
array.push(obj[key-1]);
}
if(array.length == 2){
result.push(array);
}
}
console.log(result);
I am getting the output as follows:
result = [["direct", "indirect"], ["indirect", "indir"]]
If they're all strings that have at least one character, then you can do this:
var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
var result = [];
for (var i = 1; obj[i]; i++) {
result.push([obj[i-1], obj[i]]);
}
It starts at index 1 and pushes the current and previous items in an Array. It continues as long as the values are truthy, so if there's an empty string, it'll stop.
If there could be falsey values that need to be included, then you should count the properties first.
var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
var result = [];
var len = Object.keys(obj).length;
for (var i = 1; i < len; i++) {
result.push([obj[i-1], obj[i]]);
}

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