Loop through array and apply text to n:th element - javascript

I got an array like so: ["abc", "cde", "efg"].
I want to loop through a set of elements and apply the strings from this array to each n:th (the length of the array) element.
<p>abc</p>
<p>cde</p>
<p>efg</p>
All I've managed is how to loop and apply the same string (the last one) to each element like:
<p>efg</p>
<p>efg</p>
<p>efg</p>
EDIT:
Currently I'm working with something like this:
for (var j = 0; j < noOfTableCells.length; j++) {
var heading = "";
for (var k = 0; k < myArray.length; k++) {
heading = headingArray[k];
}
}
But I can't figure out how to get it to every n:th (3rd in this case) element.

See the jsfiddle:
var elements = ["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
});
elements.forEach(function(element) {
$('body').append(element);
});
Or you could shorten it:
["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
}).forEach(function(element) {
$('body').append(element);
});
This uses jQuery. If you want to be a super random badass, you can do this (jsfiddle):
var elements = ["abc", "cde", "efg"].map(function(str) {
return '<p>' + str + '</p>';
}),
parser = new DOMParser();
elements.forEach(function(element) {
document.body.appendChild(parser.parseFromString(element, "text/xml").firstChild);
});
There are a 1000 other random, or 1000 other more efficient, solutions to this. Pick your poison.

When looping through the other elements, if there is a numbering system associated with that, you can use the numbering system. Otherwise, you can loop through those elements with a C-style for loop, as follows:
var myArray = ["abc", "cde", "efg"];
var i;
for (i = 0; i < myArray.length; i++) {
var j = i % 3;
j = (i - j) + 2;
//do something with the element that you wanted
//do something with myArray[j];
}

Eventually solved it with the following:
var laps = totalItems / myArray.length;
for (var row = 0; row < laps; row++) {
for (var cell = 0; cell < myArray.length; cell++) {
//Do the stuff
}
}

Related

Asks for a text and then iterate over the letters in a specific manner

I'm trying to solve a problem I have that requires arrays and loops.
The task is just to take a random string and write out all the letters so that it looks like this:
R, Ra, Ran, Rand ,Rando , Random, RandomS, RandomSt, RandomStr, RandomStri, RandomStrin, RandomString.
I solved that part like this:
function sometext() {
var temptext = document.getElementById("textinput").value;
var temparray = [];
temparray = temptext.slice();
for (var i = 0; i <= temparray.length; i++) {
document.getElementById("printit").innerHTML += temparray.slice(0, i) + "<br/>";
}
}
<input id="textinput" onchange="sometext()">
<div id="printit"></div>
The code runs that string that it gets from an inputbox that anyone writes in.
The next step is to have this string remove the first letter and then write it out like above so it would look like this: a, an, and, ando, andom, andomS, andomSt, andomStr, andomStri, andomStrin, andomString and then remove the first letter again so the output would be: n, nd, ndo, ndom, ndomS, ndomSt, ndomStr, ndomStri, ndomStrin, ndomString and so on until it runs out of letters to remove from. I don't know how to make it work for any amount of letters.
Example output
R
Ra
Ran
Rand
Rando
Random
a
an
and
ando
andom
n
nd
ndo
ndom
d
do
dom
o
om
m
How about a map and shift
const output = document.getElementById("printit");
function sometext(fld) {
let temptext = [...fld.value]; // or fld.value.split("")
const arr = []
while (temptext.length > 0) {
arr.push(
temptext.map((_, i) => temptext.slice(0, i + 1).join("")).join("<br>")
)
temptext.shift(); // drop first letter
}
output.innerHTML = arr.join("<br/>")
}
<input id="textinput" oninput="sometext(this)">
<div id="printit"></div>
When you get array with all needed values, just iterate through and print it as you want or to html or to console
const text = 'Random';
const result = [...text].flatMap((ch, index) => {
const righPart = text.slice(index, text.length);
const leftParts = [...righPart].map((ch, index) => righPart.slice(0, index + 1))
return leftParts;
});
console.log(result)
.as-console-wrapper{min-height: 100%!important; top: 0}
Update
It just combination of two similar functions
First return array with only right parts of string:
const text = 'Random'
[...text].map((ch, index) => text.slice(index, text.length))
// ['Random', 'andom', 'ndom', 'dom', 'om', 'm']
Second is similar and returns only left parts:
const text = 'Random'
[...text].map((ch, index) => text.slice(0, index + 1))
// ['R', 'Ra', 'Ran', 'Rand', 'Rando', 'Random']
In solution I use .flatMap() to make result array flatten. That's all.
<script>
function sometext() {
var temptext = document.getElementById("textinput").value;
var temparray = [];
temparray = temptext.slice();
for (var i = 0; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(0, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 1; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(1, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 2; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(2, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 3; i <= temparray.length; i++)
document.getElementById("printout").innerHTML += temparray.slice(3, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 4; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(4, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 5; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(5, i) + "<br/>";
if (i == temparray.length)
{
for (var i = 6; i <= temparray.length; i++)
{
document.getElementById("printout").innerHTML += temparray.slice(6, i) + "<br/>";
}
}
}
}
}
}
}
}
}
}
}
}
}
</script>
<p><input type="text" id="textinput" value=""></p>
<p><input type="button" value="Check it out" onclick="sometext()">
</p>
<div id="printout"></div>
I'm showing how I first answered it, it runs a loop and prints out the first iteration, then when i == temparray.length it starts on a new loop with i starting on the next number and prints out the next iteration and when it reaches the length of the array it starts again with the next number and this process continues for 6 iterations. Now this doesn't look very nice since it's not a generalized solution, and that's what I'm trying to figure out but with no success. As the code is now, it does it for 6 character words, in order to make it for 7 characters I just need to add another if (i == temparray.length) and for (var i = [previousNumber +1]; i< temparray.length; i++) and then write it out on the div element. It works but it isn't very pretty in my opinion.

Need to filter out repeating consecutive characters in a string using JavaScript

It is one of the challenges in Codewars, and I am supposed to write a function that will take a string and return an array, in which I can't have two consecutive identical elements. Also, the order should not change.
For example, if I pass a string "hhhhheeeelllloooooohhheeeyyy", then the function should return an array = ["h","e","l","o","h","e","y"].
This is my code.
var uniqueInOrder=function(iterable){
//your code here - remember iterable can be a string or an array
var unique = [];
for( var i = 0; i < iterable.length; i++) {
unique.push(iterable[i]);
}
for( var j = 0, k = 1; j < unique.length; j++, k = j + 1 ){
if(unique[j] === unique[k]){
unique.splice(k,1);
}
}
return unique;
}
so, if I pass a string, such as "hhhhheeeeeellllloooo",it doesn't work as I intend it to because the value of j keeps incrementing, hence I can't filter out all the identical elements.
I tried tweaking the logic, such that whenever the unique[j] === unique[k] the value of j would become zero, and if that's not the case, then things would continue as they are supposed to do.
This got me an infinite loop.
I need your help.
The second for loop is fail because unique.length is not constant during the run.
I think your problem can be solved like this:
var temp = iterable[0];
unique.push(iterable[0]);
for( var i = 1; i < iterable.length; i++) {
if(iterable[i] != temp) {
unique.push(iterable[i]);
temp = iterable[i];
}
}
Hope it helps!
You only need to compare the current index of iterable against the last character in unique:
function(iterable){
var unique = []
for(var i=0; i< iterable.length; i++){
if(unique.length < 1){
unique.push(iterable[i])
} else if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
I think this will help you:
var word="hhhhheeeelllloooooohhheeeyyy"
function doit(iterable){
var unique = []
unique[0]=iterable[0]
for(var i=1; i< iterable.length; i++){
if(iterable[i] !== unique[unique.length - 1]) {
unique.push(iterable[i])
}
}
return unique
}
alert(doit(word))
for loop will not fail because unique.length is dynamic, i.e will change with addition of new elements to array.
Tested in Internet Explorer too.
Here is the link to jsfiddle: https://jsfiddle.net/kannanore/z5gbee55/
var str = "hhhhheeeelllloooooohhheeeyyy";
var strLen = str.length;
var newStr = "";
for(var i=0; i < strLen; i++ ){
var chr$ = str.charAt(i);
//if(i==0) {newStr = chr$ };
if(chr$ == str.charAt(i+1)){
strLen = str.length;`enter code here`
}else{
newStr = newStr + chr$ ;
}
}
//document.write(newStr);
console.log(newStr);
//Answer: helohey

Searching a 2D Javascript Array For Value Index

I am trying to write a jQuery that will find the index of a specific value within a 7x7 2D array.
So if the value I am looking for is 0 then I need the function to search the 2D array and once it finds 0 it stores the index of the two indexes.
This is what I have so far, but it returns "0 0" (the initial values set to the variable.
Here is a jsFiddle and the function I have so far:
http://jsfiddle.net/31pj8ydz/1/
$(document).ready( function() {
var items = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = 0;
var line = 0;
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
$('.text').text(row + ' ' + line);
});
HTML:
<p class="text"></p>
Your if statement is comparing
if (items[i, j] == '0,')
Accessing is wrong, you should use [i][j].
And your array has values:
[1,2,3,4,5,6,7]
....
Your value '0,' is a string, which will not match numeric values inside the array, meaning that your row and line won't change.
First, you are accessing your array wrong. To access a 2D array, you use the format items[i][j].
Second, your array doesn't contain the value '0'. It doesn't contain any strings. So the row and line variables are never changed.
You should change your if statement to look like this:
if(items[i][j] == 0) {
Notice it is searching for the number 0, not the string '0'.
You access your array with the wrong way. Please just try this one:
items[i][j]
When we have a multidimensional array we access the an element of the array, using array[firstDimensionIndex][secondDimensionIndex]...[nthDimensionIndex].
That being said, you should change the condition in your if statement:
if( items[i][j] === 0 )
Please notice that I have removed the , you had after 0. It isn't needed. Also I have removed the ''. We don't need them also.
There are following problems in the code
1) items[i,j] should be items[i][j].
2) You are comparing it with '0,' it should be 0 or '0', if you are not concerned about type.
3) In your inner for loop you should be incrementing j and testing j as exit condition.
Change your for loop like bellow and it will work
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == '0') {
row = i;
line = j;
}
}
}
DEMO
Note:-
1) Better to use === at the place of ==, it checks for type also. As you see with 0=='0' gives true.
2) Better to say i < items.length and j<items[i].length instead of hard-coding it as 7.
var foo;
items.forEach(function(arr, i) {
arr.forEach(function(val, j) {
if (!val) { //0 coerces to false
foo = [i, j];
}
}
}
Here foo will be the last instance of 0 in the 2D array.
You are doing loop wrong
On place of
for (i = 0; i < 7; ++i) {
for (j = 0; i < 7; ++i) {
if (items[i, j] == '0,') {
row = i;
line = j;
}
}
}
use this
for (i = 0; i < 7; i++) {
for (j = 0; j < 7; j++) {
if (items[i][j] == 0) {
row = i;
line = j;
}
}
}
Here is the demo
looks like you are still learning how to program. But here is an algorithm I've made. Analyze it and compare to your code ;)
var itens = [[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,0,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7],
[1,2,3,4,5,6,7]];
var row = null;
var collumn = null;
for (var i = 0; i < itens.length; i++) {
for (var j = 0; j < itens[i].length; j++) {
if (itens[i][j] == 0) {
row = i;
collumn = j;
}
}
}
console.log(row, collumn);

Adding letters from a string array into each dynamic div

I am trying to add each letter of a word to dynamically generated divs .box and .boxIn but the code is just adding the last word to each box! How can I fix this, and why is his happening? And is there any way to merge two loops into one loop?
Here is the demo
And this is the code which I have:
var letters = [];
var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var letters = str.split(",");
var word = "Test App";
for (var i = 0; i < word.length; i++) {
$('<div class="box"><div class="boxIn"></div></div>').appendTo(".wrapper");
}
for (var j = 0; j < word.length; j++) {
$('.boxIn').html(word.charAt(j)).addClass('animated fadeInDown');
}
That's because you are overriding html content of all the .boxIn elements, you should use the current iterator's index for selecting the target element:
$('.boxIn').eq(j).html(word.charAt(j)).addClass('animated fadeInDown');
http://jsfiddle.net/k4spypqj/
That being said there is no need to use 2 loops. You can set the generated element's content in the first loop using either text or html method.
Fairly simple to combine these which will make it more efficieent and get rid of the html over ride bug you have
var letters = [];
var str = "A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z";
var letters = str.split(",");
var word = "Test App";
for (var i = 0; i < word.length; i++) {
$('<div class="box"><div class="boxIn animated fadeInDown">'+
word.charAt(i)+'</div></div>').appendTo(".wrapper");
}
DEMO
The problem is the way you set the html. You select all elements with the class boxIn and set the char at position j to the html (of all elements).
To only set the char to to a single element you can limit the selection by using the .eq() function.
In your case that would be:
for (var j = 0; j < word.length; j++) {
$('.boxIn').eq(j).html(word.charAt(j)).addClass('animated fadeInDown');
}
If you want to merge your two loops, you can set the value directly in your html string:
for (var i = 0; i < word.length; i++) {
$('' + word.charAt(i) + '').appendTo(".wrapper").children('.boxIn').addClass('animated fadeInDown');
}
or if you would add it separatly:
for (var i = 0; i < word.length; i++) {
$('<div class="box"><div class="boxIn"></div></div>').appendTo(".wrapper").children('.boxIn').addClass('animated fadeInDown').html(word.charAt(i));
}
jsfiddle

Count numbers and output one char at time

I've tried hard, but I just can't figure it out.
I want to output numbers, but only one character of the number at time. I need to create something like this:
This should be created within a for-loop:
http://jsfiddle.net/jv7H8/
But as you can see there is more than one character in a cell when number > 10.
The desired result should be for example:
1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1, 1, 2, 1, 3, 1, 4....
Any suggestions? :)
First concatenate the numbers into a string:
var s = '';
for (var i = 1; i <= 42; i++) s += i.toString();
Then loop the characters in the string:
for (var i = 0; i < s.length; i++) {
// output s[i]
}
Here is your jsfiddle updated with my approach: http://jsfiddle.net/jv7H8/2/
The pertinent aspects that I changed was adding a for loop that processed through the length of the number you were going to output:
var str = number.toString(); // the current number as you're looping through
for (var k = 0; k < str.length; k++) {
var oneLetterAtATime = str.charAt(k); // get the digits one at a time
output += "<td>" + oneLetterAtATime + "</td>";
}
number++;
Edit: If you need there to only be nineteen columns, then you'll need to update your column counter for every instance where you are displaying another <td> but not looping back around to increment your column counter. I.e.,
if (k > 0) {
j++;
}
Here is an updated version displaying how this would work: http://jsfiddle.net/jv7H8/21/
Notably, there isn't a very good way to not go past the 19th column when you are in the middle of displaying a number in the 19th column that has more than one digit.
Take all the characters in a string like this:
var t = '';
var limit=100;
for (var j = 1; j<= limit; j++) t += j.toString();
var output='';
for (var j = 0; j < t.length; j++) {
output=output+','+t[i];
}
alert(output);
Please check your updated fiddle here
This will server your purpose.
Following is the code, most of it is your code only:
rows = 3;
columns = 19;
number = 1;
var str = "";
output = '<table style="width:100%;">';
for(var i = 0; i < rows; i++) {
output += "<tr>";
for(var j = 0; j < columns; j++) {
output += "<td>" + number + "</td>";
str +=number;
number++;
}
output += "</tr>";
}
output += "</table>";
$("#game").html(output);
var strvalue="";
$.each(str, function(e,v){
if (e > 0){
strvalue = strvalue + ", "+ v;
}
else{
strvalue += v;
}
});
alert(strvalue);

Categories