Output variables one by one from array - reactjs

how do I pull variables from array one by one? I want to make a card with one saying Zlin, second Praha, etc... The way it works now is that it outputs all of them at once 4x. Thank you.
const KartyLoop = () => {
var mesta = ['Zlin','Praha','Ostrava','Brno']
var lokace = []
for (var i=0; i < mesta.length; i++)
{
lokace += mesta + "\n"
}
return (<Text>{lokace}</Text>);
}

Your code pushes the array itself and not its values.
If I understand correctly you want to copy an array.
You would want to do this.
const KartyLoop = () => {
var mesta = ['Zlin','Praha','Ostrava','Brno']
var lokace = []
for (var i=0; i < mesta.length; i++)
{
lokace += mesta[i] + "\n"
}
return (lokace);
}

Related

Why my array getting appended instead of clearing and Adding new data

I am trying to achieve a method in which the array steps got filled with new data every time I click on the button of Create New array, but instead of that, the data is getting appended instead of updating.
here are my states :
const [arr , setArray] = useState(createArray())
const [steps , setSteps] = useState([]);
const [selectedAlgorithm , setSelectedAlgorithm] = useState ();
here is my create new Array function :
const handleCreateNewData = ()=>{
let newarr = createArray();
setArray ([]);
setArray([...newarr]);
setSteps ([]);
setTimeout(()=>{
if ( algorithms[selectedAlgorithm] !== undefined){
algorithms[selectedAlgorithm](arr, steps , setSteps);
console.log('running')
}
},2000)
}
here is my bubble sort algorithm :
export const BubbleSort = (array , steps ,setSteps) =>{
let funarray = new Array();
funarray = [...array] ;
for (let i = 0 ; i < funarray.length-1 ; i++){
for(let j = 0 ; j < funarray.length-1 ; j++){
if(funarray[j]>funarray[j+1]){
[funarray[j],funarray[j+1]] = [funarray[j+1],funarray[j]]
setSteps([...steps, funarray])
steps.push(funarray.slice());
console.log('Working')
}
}
}
return funarray;
}
What is supposed to do is every time I click on create new array it should generate a new set of arrays but instead of creating new arrays it just appending the new arrays in the old steps.
You can create a temp array to hold the steps, then when the loops are done, call setSteps:
const BubbleSort = (array, steps, setSteps) => {
let funarray = [];
funarray = [...array];
let temp = [];
for (let i = 0; i < funarray.length - 1; i++) {
for (let j = 0; j < funarray.length - 1; j++) {
if (funarray[j] > funarray[j + 1]) {
[funarray[j], funarray[j + 1]] = [funarray[j + 1], funarray[j]];
temp.push(funarray)
}
}
}
setSteps(temp);
return funarray;
};
Sample: https://codesandbox.io/s/cool-wind-ijj7z?file=/src/App.js

How do you dynamically create unpacked variable names using destructuring syntax in JS ES6? [duplicate]

How can I use a for loop to dynamically create variables, and be returned.
function createVariables()
{
for ( i=0; i<=20; i++ )
{
var account = i;
return var account + i;
}
}
The goal is to have the result below:
var account1;
var account2;
var account3; and etc.....
You should use an array:
function createVariables(){
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "whatever";
}
return accounts;
}
You then have access to accounts[0] through accounts[20].
The only way I know how to do this would be to use the JavaScript eval function.
Something like eval("account" + 1 + "='some value'");
http://www.w3schools.com/jsref/jsref_eval.asp
However, I think #Domenic has a better answer.
I was unsure about answering an old question however I stumbled across this while seeking an answer myself.
for (var i = 1; i < 11; i++) { // Creating 10 objects
window["Object"+i] = new Object();
}
console.log(Object7); // is not undefined
The above code loops to 10 while creating dynamic objects, as described on https://www.codecademy.com/en/forum_questions/51068e93f73ad4947a005629
I find this a simplest solution
for (var i = 0; i < 10; i++) {
this["RONAK"+i] = "MY VAL";
}
Output
RONAK0 = "MY VAL"
RONAK1 = "MY VAL"
RONAK2 = "MY VAL"
...
RONAK9 = "MY VAL"
You can use the eval() method to declare dynamic variables as it executes JavaScript statements passed to it.
function createVariables()
{
for ( i=0; i<=20; i++ )
{
var str ="account"+ i+" = undefined";
//Declaring and Setting dynamic variable to undefined using eval
eval(str);
}
}
createVariables();
let etc = { name: 'foobar', city: 'xyz', company: 'companyName' };
Object.keys(etc).forEach(key=>{
window[`${key.toUpperCase()}`] = new Object(`${etc[`${key}`]}`)
});
console.log("-->"+NAME) //foobar
this is similar to what #whatevermike describes but it does not work in NodeJS because it uses window. :(
function createVariables() {
var accounts = [];
for (var i = 0; i <= 20; ++i) {
accounts[i] = "merhaba" + i;
}
return accounts;
}
The following code will actually create variables, instead of creating this sort of hash table proposed by #Domenic
function createVariables(){
var varName = "accounts";
for (var i = 0; i <= 20; ++i) {
eval('var ' + varName + i + ' = ' + '"whatever"' + ';');
}
return accounts;
}
I was pretty proud of the way I made iterating variables with my code, was going to share it but I think I'll just sort of show you modified version of it.
function variableBuilder() {
let i = 0;
while (i <= 20) {
let accountVariable = "account".concat(i);
`// variable can even be reassigned here`
console.log(accountVariable);
i++;
}
}
you can use the variable as an iterating variable identifier, in the spot that I suggested; I used this method to build DOM nodes, to create a dynamically built HTML table.
we can use map for it.
var map = {};
for (var i = 0; i < 10; ++i) {
map["nutrient" + i] = "some stuff" + i;
}
console.log(map)
result:
{
nutrient0: 'some stuff0',
nutrient1: 'some stuff1',
nutrient2: 'some stuff2',
nutrient3: 'some stuff3',
nutrient4: 'some stuff4',
nutrient5: 'some stuff5',
nutrient6: 'some stuff6',
nutrient7: 'some stuff7',
nutrient8: 'some stuff8',
nutrient9: 'some stuff9'
}
the easiest method is to use eval and write the variable declaration line inside a loop that follows your conditions
for (let i = 0; i <= 3; i++) {
eval(`var variable${i}=${i}`);
eval(`console.log(variable${i})`)
}
//Output:
0
1
2
3
You can also console log the values outside as they are declared global with the var keyword

converting an object to an array in angular2 typescript

I have an object within an object and i would like to convert the inner one to a string separated comma but it generates an infinite loop
After an observable http request am getting the data this way
this._categoryService.getChecklistCategories()
.subscribe(
res => {
this.categories = res;
let newitem:string[];
for(var i=0; i<res.length; i++){
this.categories.map((category, i) => category.no = i+1);
var obj = res[i].assigned; //an obect.
console.log(obj[0]); //get the first index
}
})
The above console.log(obj[0]) generates
I would like to create a string of truck_subtype and append it to this.categories
I have tried the following
res => {
this.categories = res;
let newitem:string[];
for(var i=0; i<res.length; i++){
this.categories.map((category, i) => category.no = i+1);//this adds no i,2,3...
var obj = res[i].assigned; //array item
let stringArray: Array<any> = [];
for(var i=0; i<obj.length; i++){
stringArray.push(obj[i].truck_subtype);
}
this.categories.map((category, i) => category.assigned= stringArray)
}
}
The above generates an infinite loop and fails to add the string of array to this.categories
Where am i wrong
May be the i variable that are declared four times (in for's and in map's), I think your index never gets to the res.length because when you use map you are resigning it.
Try to change the i's inside map to another name like i2..., and test it to see if the loops goes away.
res => {
this.categories = res;
let newitem:string[];
for(var i=0; i<res.length; i++){
this.categories.map((category, i2) => category.no = i+1);//this adds no i,2,3...
var obj = res[i].assigned; //array item
let stringArray: Array<any> = [];
for(var i3 =0; i<obj.length; i++){
stringArray.push(obj[i3].truck_subtype);
}
this.categories.map((category, i4) => category.assigned= stringArray)
}
}

Splice array within array

How can I splice an array within another array?
I'm trying to create a game for kids in my class. Some kind of a trivia history question creator. How to splice the MasterArray so that I would get rid of sub-arrays (Hard-England and Medium-England) within the allEnglandArray. Because the "MasterArray.splice()" seem to be affecting - splicing only the allEngland array, or the allFrance array. But I need to get rid of those sub-arrays...
My code:
var Easy-England:Array = ["item1","item2","item3","item4","item5"];
var Medium-England:Array = ["item6","item7","item8"];
var Hard-England:Array = ["item9","item10"];
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
var Easy-France:Array = ["item11","item12","item13","item14","item15"];
var Medium-France:Array = ["item16","item17","item18"];
var Hard-France:Array = ["item19","item20"];
var allFrance:Array = [Easy-France,Medium-France,Hard-France];
// the list of countries goes on and on and on... (Italy, Hungary, etc.)
var allStuff:Array = [allEngland, allFrance, etc.];
var MasterArray:Array;
// FUNCTIONS
// clear MasterArray - first I clear out completely the MasterArray
function clearMasterArray():void
{
MasterArray.splice(0);
}
// update MasterArray - than I fill the MasterArray with data according to checkBoxes
function updateMasterArray():void
{
for (var i:int = 0; i<checkBoxBlock.myCheckBoxes.length; i++)
{
if (checkBoxBlock.myCheckBoxes[i].selected)
{
MasterArray.push(allStuff[i]);
}
}
}
// splice MasterArray - last thing I do is splice the items according to student's proficiency level, referred to as "studentPL".
function spliceMasterArray():void
{
if (studentPL == 1)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(5,5);
}
}
if (studentPL == 2)
{
for (var i:int = 0; i<allStuff.length; i++)
{
allStuff[i].splice(8,2);
}
}
if (studentPL == 3)
{
for (var i:int = 0; i<allStuff.length; i++)
{
trace("no need to splice");
}
}
}
And after this I call those functions in another function in this order...
function creatorFunction():void
{
clearMasterArray();
updateMasterArray();
spliceMasterArray();
}
Instead of:
var allEngland:Array = [Easy-England,Medium-England,Hard-England];
try this:
var allEngland:Array = Easy-England.concat(Medium-England, Hard-England);
This way you will have a 'flat' array (no sub-arrays), so it will be easier to deal with.

Randomly removing an array

just for the record, i'm using AS3.
I have an issue where I would like to remove a sprite randomly in AS3, I have managed to figure out how to create the sprites so that they fill as a grid, just for the life of me I can't figure out how to remove them!
Here's the code i've used to create them:
function showpixels() : void
{
for (var i:int = 0; i < 40; i++)
{
for (var j:int = 0; j < 40; j++)
{
var s:Sprite = new Sprite();
s.graphics.beginFill(0);
s.graphics.drawRect(i*10, j*10, 10, 10);
s.graphics.endFill();
addChild(s);
pixels.push(s);
}
}
}
Basically I need these to be removed randomly until what's underneath can be seen.
Any help would be good, I'm pretty new to this! Thanks!
function removeRandom():void
{
var rand:uint = Math.random()*pixels.length;
var i:Sprite = Sprite(pixels[rand]);
if(i.parent) i.parent.removeChild(i);
pixels.splice(rand, 1);
}
UPDATE: To remove at random intervals you could try something like this:
var _timer:int = 100;
addEventListener(Event.ENTER_FRAME, _handle);
function _handle(e:Event):void
{
if(pixels.length > 0) _timer --;
if(_timer < 1)
{
_timer = 10 + Math.random()*50;
removeRandom();
}
}
function removeRandom():void
{
var rand:uint = Math.random()*pixels.length;
var i:Sprite = Sprite(pixels[rand]);
if(i.parent) i.parent.removeChild(i);
pixels.splice(rand, 1);
}
Marty's idea works. Another option would be to shuffle the array first and then just pop off elements.
To shuffle an Array use pixels.sort(function (...args):int { return int(2*Math.random()-1) }).
And then you can simple remove them like this:
function remove():void {
if (pixels.length) removeChild(pixels.pop());
else clearInterval(this.id);
}
And add this line at the end of showpixels:
this.id = setInterval(remove, 500);

Resources