How to separate a string by words using arrays and function? - javascript

Code the I am trying to do:
function look(str) {
var stringArr = ['JAVA'];
var arr = [];
var novaString = ''
for(i = 0; i < stringArr.length; i++) {
arr = stringArr;
}
console.log(arr)
return arr;
} look('arr');
I Want the output to look like this:
[J]
[JA]
[JAV]
[JAVA]
[JAV]
[JA]
[J]
There's no more details to add.

This will do
var k='JAVA';
var a=k.split('');
var e=[];
a.forEach((el)=>{
e.push(el);
console.log(e);
})
for(let i=0;i<a.length-1;i++)
{
e.pop();
console.log(e);
}

Your question is not so clear but may be you want this:
function look(str) {
var stringArr = str;
for(i = 0; i < stringArr.length; i++)
{
console.log("[" + stringArr.substring(0,i+1) + "]");
}
for(i = (stringArr.length - 2); i >= 0; i--)
{
console.log("[" + stringArr.substring(0,i+1) + "]");
}
}
look('arr');

Related

problem using .split() method in a function but it works on console.log

the problem is only in the bottom function objectPutter
specifically the line with wowza.split(' '); labelled with the comment
let eq
let x = null
let bracketNum = 0
let k = 0
let pre = 0
class subEqCreator { //subEq object
constructor() {
this.precede = 0;
this.text = '';
}
parser() {
this.text += eq[k]
}
ma() {
this.text.split(' ')
}
};
function trigger() { //used for HTML onClick method
show();
brackets();
subEqDynamic()
parseEquation();
objectPutter()
};
function show() {
const recent = document.querySelector("ol");
const txt = document.getElementById('input');
eq = txt.value;
li = document.createElement('li');
li.innerText = eq;
recent.appendChild(li);
txt.value = '';
};
function brackets() { //counts how many brackets appear
for (let i = 0; i < eq.length; i++) {
if (eq[i] == "(") {
bracketNum++;
};
};
};
let subEqDynamic = function() { // creates a new object for each bracket
for (let count = 0; count <= bracketNum; count++) {
this['subEq' + count] = x = new subEqCreator()
};
};
function parseEquation() { // assign characters to SubEq object
let nextIndex = 0;
let currentIndex = 0;
let lastIndex = [0];
let eqLen = eq.length;
let nex = this['subEq' + nextIndex]
for (k; k < eqLen; k++) {
if (eq[k] == "(") {
nextIndex++;
pre++
this['subEq' + currentIndex].text += '( )';
this['subEq' + nextIndex].precede = pre;
lastIndex.push(currentIndex);
currentIndex = nextIndex;
} else if (eq[k] == ")") {
pre--
currentIndex = lastIndex.pop();
} else {
this['subEq' + currentIndex].parser()
}
}
}
function objectPutter() {
for (let i = 0; i < bracketNum; i++) {
let wowza = this['subEq' + i].text
wowza.split(' '); // 🚩 why isnt it working here
console.log(subEq0);
for (let j = 1; j <= wowza.length; j += 2) { // for loop generates only odds
let ni = i++
wowza.splice(j, 0, this['subEq' + ni])
console.log(i)
}
}
}
to fix this i tried;
making a method for it ma() in the constructor.
putting in the function parseEquation above in case it was a scope issue.
also, i noticed subEq0.split(' ') worked in browser console even replicating it to the way i done it using this['subEq' + i].text.split(' ') where i = 0.
After it runs the it says .splice is not a function and console.log(subEq0) shows subEq0.text is still a string
.split() does not change the variable it returns the splitted variable

How do I fix the undefined result I keep getting from this?

So I'm doing the HackerRank superDigit challenge and even though I have the correct value for all the informal test cases, the Output box says that the result is undefined.
I'm not really getting what undefined is all about or how a variable with a value returns as undefined.
function superDigit(n, k) {
// Write your code here
var nArr = [];
for(let i = 0; i < n.length; i++)
{
nArr.push(n[i]);
}
console.log('nArr: ' + nArr);
var nComb = 0;
for(let i = 0; i < nArr.length; i++)
{
nComb += parseInt(nArr[i]);
}
console.log('nComb: ' + nComb);
var nMult = nComb *= k;
console.log('nMult: ' + nMult);
console.log('');
if(nMult < 10)
{
return nMult;
}
else
{
superDigit(nMult.toString(),1);
}
}
You probably want to return the superDigit result as well. So when calling superDigit recursively, add the return statement. I also cleaned up the console.log calls a bit so its more readable to me.
function superDigit(n, k) {
var nArr = [];
for(let i = 0; i < n.length; i++)
{
nArr.push(n[i]);
}
var nComb = 0;
for(let i = 0; i < nArr.length; i++)
{
nComb += parseInt(nArr[i]);
}
var nMult = nComb *= k;
console.log('nMult:', nMult, 'nArr:', nArr, 'nComb:', nComb);
if(nMult < 10)
{
return nMult;
}
else
{
return superDigit(nMult.toString(),1);
}
}
document.getElementById('result').innerText = superDigit("200", 20);
<html>
<body>
<p id="result"></p>
</body>
</html>

How to create n different arrays with 6 random numbers each. - Javascript/Jquery

I want to create 1 - 12 arrays of 6 random numbers each.
At the moment I can only create one. So I don't know how to loop this.
This is my code so far:
<script type="text/javascript">
function schleife() {
var arr = [];
var krams = [];
for(i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}
arr.push(krams.toString() + "<br /><br />");
$(".bsp2").append(arr);
}
function uebertrag() {
schleife();
}
</script>
You need to create new function: e.g. getArrayOfRandomNumbers
function getArrayOfRandomNumbers() {
var krams = []
for(var i=1; i<=6; i++) {
var zufall = Math.floor((Math.random() * 49) + 1)
krams.push(zufall++)
}
return krams
}
And now you can invoke this function in loop:
for (var j = 0; j < 12; j++) {
var arrayOfRandomNumber = getArrayOfRandomNumbers()
//do something with this array, e.g. append
$(".bsp2").append(arrayOfRandomNumber.toString())
}
function schleife(iRange, jRange) {
var array = []
for (i = 1; i <= iRange; i++) {
var krams = [];
for(j = 1; j <= jRange; j++) {
var zufall = Math.floor((Math.random() * 49) + 1);
krams.push(zufall++);
}
array.push(krams);
$(".bsp2").append(krams + "<br /><br />");
}
return array;
}
schleife(12, 6);
Thank you havenchyk. I was able to make it with your code!
Great! I'm really happy up to this point. ;-)
That's how it looks now:
function getArrayOfRandomNumbers() {
var krams = [];
while(krams.length < 6) {
var zufall = Math.floor((Math.random() * 49) + 1);
var found = false;
for(var i=0; i<krams.length; i++) {
if(krams[i] == zufall) {
found = true;
break
}
}
if(!found){
krams.push(zufall++);
}
}
return krams;
}
function getArrays() {
function compareNumbers(a, b) {
return a - b;
}
var results = [];
for (var j = 0; j <= 10; j++) {
var arrayOfRandomNumber = getArrayOfRandomNumbers();
//do something with this array
results.push(arrayOfRandomNumber.splice(0, 6).sort(compareNumbers).toString()+"<br /><br />");
}
$(".bsp2").append(results[1]);
$(".bsp2").append(results[2]);
$(".bsp2").append(results[3]);
$(".bsp2").append(results[4]);
$(".bsp2").append(results[5]);
$(".bsp2").append(results[6]);
$(".bsp2").append(results[7]);
$(".bsp2").append(results[8]);
$(".bsp2").append(results[9]);
$(".bsp2").append(results[10]);
}

how do i get non-repeated character and its count in JavaScript?

Here is my code. What should I modify of this code to get the output as
"T-1
r-1
a-1
e-1 "
(other characters are repeating. So no need to print the others)
function different() {
var retureArr = [];
var count = 0;
var complete_name = "Trammell";
var stringLength = complete_name.length;
for (var t = 0; t < stringLength; t++) {
for (var s = 0; s < stringLength; s++) {
var com1 = complete_name.charAt(t);
var com2 = complete_name.charAt(s);
if (com1 != com2) {
retureArr[count] = com1;
count++;
}
}
count = 0;
}
}
I think this is what you want. You need to count the number of occurrences of each character in a dictionary. Then you can print them based on the count being equal to 1.
var retureArr = [];
var complete_name = "Trammell";
for (var i = 0; i < complete_name.length; i++)
{
var key = complete_name[i];
if (!(key in retureArr))
{
retureArr[key] = 1;
}
else
{
retureArr[key] = retureArr[key] + 1;
}
}
var output = "";
for (var key in retureArr)
{
if (retureArr[key] == 1)
{
output += key + "-" + retureArr[key] + " ";
}
}
alert(output);
This alerts the following string:
T-1 r-1 a-1 e-1
This works. but perhaps isn't the most efficient!
var string = "input string";
var stringList = [];
var outputString = "";
for (var i=0; i < string.length; i++){
var charObject = {"Char": string.charAt(i), "Passed": false};
stringList.push(charObject);
}
for (var i=0; i < stringList.length; i++){
if(!stringList[i].Passed && stringList[i].Char != " "){
var currentCount = countOccurrences(string, stringList[i].Char);
if(currentCount == 1){
outputString += stringList[i].Char+"-"+currentCount + " ";
}
stringList[i].Passed = true;
}
}
console.log(outputString);
function countOccurrences(string, char){
var count = 0;
for (var i=0; i < string.length; i++){
if(string.charAt(i) == char){
count++;
}
}
return count;
}

Protractor:How to store values in array and then to do sorting

I need to sort list strings under the table ,so for that i have written following lines of code but on console i am not getting any values:
var j = 9;
var rows = element.all(by.repeater('row in renderedRows'));
var column = element.all(by.repeater('col in renderedColumns'));
expect(rows.count()).toEqual(5); //here its printing number of rows
expect(column.count()).toEqual(5); //here its printing number of columns
var arr = [rows.count()];
for (var i = 0; i < rows.count(); i++) {
console.log("aai" + i);
if (i = 0) {
//var columnvalue=column.get(9).getText();
var columnvalue = column.get(9).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the value first value of column
console.log("value1" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("aa" + ss.trim());
});
} else {
var j = j + 8;
var columnvalue = column.get(j).getText().then(function(ss) {
return ss.trim();
arr[i] = ss.trim(); //here it will save the other values of column
console.log("value" + arr[i]);
expect(arr[i]).toEqual('DN');
console.log("ab" + ss.trim());
});
}
}
Sorting_Under_Table: function(col){
test = [];
var m;
var dm = 0;
element(by.xpath('//div[#class="ngHeaderScroller"]/div['+col+']')).click();
element.all(by.repeater('row in renderedRows')).then(function(row) {
m = row.length;
for (i = 1; i <= row.length; i++)
{
user_admin_table_name = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+i+']/div['+col+']'));
user_admin_table_name.getText().then(function(text) {
var test_var1 = text.toLowerCase().trim();
test.push(test_var1);
var k = test.length
if (k == m){
for (j = 0; j < test.length; j++){
test.sort();
d=j+1;
user_admin_table_name1 = browser.driver.findElement(by.xpath('//div[#class="ngCanvas"]/div['+d+']/div['+col+']'));
user_admin_table_name1.getText().then(function(text1) {
var test_var2 = text1.toLowerCase().trim();
if (test_var2 == test[dm]){
expect(test_var2).toEqual(test[dm]);
dm = dm +1;
}else {
expect(test_var2).toEqual(test[dm]);
log.error("Sorting is not successful");
dm = dm +1;
}
});
}
}
});
}
});
},
You can use this code for sorting and verifying is it sorted or not
I'm not sure how your above example is doing any sorting, but here's a general solution for trimming and then sorting:
var elementsWithTextToSort = element.all(by.xyz...);
elementsWithTextToSort.map(function(elem) {
return elem.getText().then(function(text) {
return text.trim();
});
}).then(function(trimmedTexts) {
return trimmedTexts.sort();
}).then(function(sortedTrimmedTexts) {
//do something with the sorted trimmed texts
});

Categories

Resources