Merge array into a new array javascript in a loop
Hi all i have this loop which will loop 4 times.
for (var i = 0; i < 4; i++){
var d = [[1111,2222],[3333,4444]]
}
below is my expect output , thank you every much all.
var expected = [
[
[1111,2222],[3333,4444]
],
[
[1111,2222],[3333,4444]
],
[
[1111,2222],[3333,4444]
],
[
[1111,2222],[3333,4444]
]
]
2 answers
-
answered 2022-01-19 16:43
dporechny
Is that what you tried to achieve?
const output = []; const input = [[1111,2222],[3333,4444]] for (var i = 0; i < 4; i++){ output.push(input) } console.log(output) // [[[1111,2222],[3333,4444]], [[1111,2222],[3333,4444]], [[1111,2222],[3333,4444]], [[1111,2222],[3333,4444]]]
-
answered 2022-01-19 16:44
lucky930
You can get the result like this
function getNewArray() { var newArray = [] for (var i = 0; i < 4; i++){ var d = [[1111,2222],[3333,4444]] newArray.push(d) } return newArray; } let expected = getNewArray()
do you know?
how many words do you know
See also questions close to this topic
-
how to change prettier format for react native
my code formatting prettier didn't works well for react native, i don't understand where to config it but it works well with flutter
from this code
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( <View> <Text>Apps</Text> </View> ) }
it's formatted to this
import { View, Text } from 'react-native' import React from 'react' export default function App() { return ( < View > < Text > Apps < /Text> < /View> ) }
-
MarkLogic server-side JavaScript and XQuery
I am just starting using NoSQL MarkLogic DB and trying to choose for me the best query language to learn and use in future. On server side MarkLogic provides the possibility to use JavaScript API or XQuery API.
I want to receive an advice. Which language is better to concentrate on and learn? JavaScript or XQuery?
- Popover in chrome extension using js
-
How to get pass an array through a function with a user input?
I want to ask the user for the size of a 2D array arr[][], but also pass it through the function initializeArray. However, if I pass it through the function, I would have to have a size declarator for col, which doesn't allow the user to enter their own value for the size
#include<iostream> using namespace std; void initializeArray(arr[][10], int N); int main() { int N; cout << "enter an array size: "; cin >> N; int arr[N][N]; initializeArray(arr, N); // I get an error here for(int i = 0; i < N; i++) { for(int j = 0; j < N; j++) cout << arr[i][j] << " "; cout << endl; } } void initializeArray(int arr[][10], int N) { for(int i = 0; i < N; i++) for(int j = 0; j < N; j++) arr[i][j] = 0; }
The only solution I found was the make arr[][] a global array, but in that case, I would have to still declare the size parameters, and I want the user to enter whatever they want. Is there another way to fix this?
-
Two-dimensional array C++
Problem: Write a program of a two dimensional integer array of exactly four rows and four columns, and find the sum of the integers each row of the array as well as determine the smallest inputted element/data in the array. The user will input the elements. Display the elements in tabular form. Make the program user friendly. Use a Class and a member function for the process involve.
-
Pass Associative Array from Symfony Controller to Twig and JavaScript
So, I have 2 arrays that I've combined into one array after making sure they're the same length as such.
//Fetching Ratings for All Coaches & Making a Key, Value Associative Array with Coach id as Key and Rating as Value $coaches = $coachRepository->findAll(); $rating = $coachRepository->findRatingByCoach(); //Array of coach IDs $id_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); } $combined = array_combine($id_array, $rating);
Now I want to pass this key, value array to Twig template and JavaScript. I'm currently doing this
return $this->render('...', [ ..., 'combined'=>$combined ]);
And I'm accessing the array in Twig as such
{% for key, value in combined %} {{ key }} - {{ value }} {% endfor %}
And I'm getting this error.
Object of class App\Entity\Coach could not be converted to string
Looking at the Stack Trace I can see that the array combined is being passed in this form.
'combined' => array(object(Coach))
After a bit of debugging it turns out that I thought the issue was with the $
id_array
when in fact it's the $rating
variable that's presenting an issue. I'm not sure why but I'm getting a single float value. I fixed the issue by changing how I'm fetching the $rating, now instead of using a QueryBuilder to get it from the DB, I'm getting it from list of Coaches as such//Array of coach IDs and array of Ratings $id_array = array(); $rating_array = array(); foreach ($coaches as $c){ $id_array[] = $c->getId(); $rating_array [] = $c->getRating(); }
Even if I set the array
-
react-router-dom v6 params only numbers
I want add number regex in may param in react-router-dom v6. it work fin in v5 like it:
<Route path="list/:id(\d+)" element={<MyComponent/>} />
but it not work in v6.
-
How can I fixed my problem"FirebaseError: Firebase: Error (auth/invalid-api-key)."
My environment variable is ok. No comas and name mistakes but they given me error like "FirebaseError: Firebase: Error (auth/invalid-api-key)". How can I fixed it. Please Help me...
This my .env file
REACT_APP_apiKey=AIzaSyBWobnhbdeMdNpXXXXXXXXXXXXXXXXXXXX REACT_APP_authDomain=XXXXX.firebaseapp.com REACT_APP_projectId=XXXX REACT_APP_storageBucket=XXXXX.appspot.com REACT_APP_messagingSenderId=4997390XXXXX REACT_APP_appId=1:4997390XXXXX:web:cc7bc80aa1bdb78fXXXXXX REACT_APP_measurementId=G-M1XDXXXXXX
This my firebase config file
const firebaseConfig = { apiKey: process.env.REACT_APP_apiKey, authDomain: process.env.REACT_APP_authDomain, projectId: process.env.REACT_APP_projectId, storageBucket: process.env.REACT_APP_storageBucket, messagingSenderId: process.env.REACT_APP_messagingSenderId, appId: process.env.REACT_APP_appId, measurementId: process.env.REACT_APP_measurementId, }; when I debugging firebaseConfig object console.log(firebaseConfig.apiKey); ==========> undefined console.log(firebaseConfig.authDomain); ==========> undefined console.log(firebaseConfig.projectId); ==========> undefined console.log(firebaseConfig.storageBucket); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined console.log(firebaseConfig.appId); ==========> undefined console.log(firebaseConfig.measurementId); ==========> undefined
client side given error this "FirebaseError: Firebase: Error (auth/invalid-api-key)"
-
How to convert String having key=value pairs to Json
myString =
{AcquirerName=abc, AcquiringBankCode=0.2, ApprovalCode=00};
I want to convert it to the following string.
{"AcquirerName": "abc", "AcquiringBankCode": 0.2, "ApprovalCode": 0};
How can I do it in java?
-
Fetch doesn't retrive data
I am currently building a login form which will be using a restAPI for the registration/Auth but I'm receiving a 401 error when using fetch to test the retrieved data.
console.log(fetch('http://localhost:5000/users/'), { method: 'get', headers: { 'Content-Type': 'application/json' }, })
.then(res => res.json()) .then(json => console.log(json))</code>
-
NextJS: Error serializing `.data.data` returned from `getServerSideProps`
I'm new to NextJS. I'm working on a simple page in which I need to retrieve data from my backend app. My backend app is a totally separate app written in go. My undestanding is that I must use
getServerSideProps
to get data from the server on load, so I've got the following:myProject/pages/category/new.js
:export default function AddNewCategory(data) { ... } export const getServerSideProps = async () => { const data = await getAllCategories(); console.log(await data) return { props: { data: { data } } }; };
myProject/api/category.js
:import axios from "axios"; // getAllCategories returns a list of all active categories export const getAllCategories = async() => { axios.get("http://127.0.0.1:8080/api/v1/categories") .then(function (response) { console.log(response.data) return response.data; }) .catch(error => { console.error("error") console.log(error) }) }
As you can see I've got a print statement in
getAllCategories
which prints:{ data: [ { id: 1, name: 'Pop', slug: 'pop', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:00-04:00', updated_at: '2022-05-03T19:50:00-04:00', deleted_at: null }, { id: 3, name: 'Pop 2', slug: 'pop-2', description: 'Pop', parent: 0, active: true, created_at: '2022-05-03T19:50:24-04:00', updated_at: '2022-05-03T19:50:24-04:00', deleted_at: null } ] }
yet I'm getting the following error:
error - Error: Error serializing
.data.data
returned fromgetServerSideProps
in "/category/new". Reason:undefined
cannot be serialized as JSON. Please usenull
or omit this value.I saw around that I should try to convert the data to string and then back to json:
return { props: { data: JSON.parse(JSON.stringify(data)) } };
but when I do this I'm getting a different error:
error - SyntaxError: Unexpected token u in JSON at position 0
I'm using
next@12.1.5
Any idea what's going on?
-
I ned a while loop statment that makes the calculations loop and ask again
im not too sure how you add a loop statement to this. I want it to be a while loop that makes it do that the calculations repeat after finishing. I've tried but it just keeps on giving me errors. ive tried doing While statements but just will not work im not sure how you set it up as my teacher did not explain very well
import com.godtsoft.diyjava.DIYWindow; public class Calculator extends DIYWindow { public Calculator() { // getting number one double number1 = promptForDouble("Enter a number"); //getting number2 int number2 = promptForInt("Enter an integer"); //getting what to do with operation print("What do you want to do with these numbers?\nAdd\tSubtract\tMultiply\tDivide"); String operation = input(); //declaring variable here so the same one can be used double answer = 0; switch(operation) { case "add": answer = number1 + number2; print(number1 + " + " + number2 + " = " + answer); break; case "subtract": answer = number1 - number2; print(number1 + " - " + number2 + " = " + answer); break; case "multiply": answer = number1 * number2; print(number1 + " * " + number2 + " = " + answer); break; case "divide": try { answer = number1 / number2; } catch(ArithmeticException e) { print("A number cannot be divided by 0."); } print(number1 + " / " + number2 + " = " + answer); break; } double double1 = promptForDouble("Enter a number"); double double2 = promptForDouble("Enter another number"); double double3 = promptForDouble("Enter one last number"); print("What do you want to do with these numbers?\nAdd\tSubtrack\tMultiply\tDivide"); String operation2 = input(); double answer2 = 0; switch(operation2) { case "add": answer2 = double1 + double2 + double3; print(double1 + " + " + double2 + " + " + double3 + " = " + answer2); break; case "subtract": answer2 = double1 - double2 - double3; print(double1 + " - " + double2 + " - " + double3 + " = " + answer2); break; case "multiply": answer2 = double1 * double2 * double3; print(double1 + " * " + double2 + " * " + double3 + " = " + answer2); break; case "divide": try { answer2 = double1 / double2 / double3; } catch(ArithmeticException e) { print("A number cannot be divided by 0."); } print(double1 + " / " + double2 + " / " + double3 + " = " + answer2); break; } want it to loop after the code on top } private double promptForDouble(String prompt) { double number1 = 0; print(prompt); String number = input(); try { number1 = Double.parseDouble(number); } catch(NumberFormatException e){ print("That is not a number. Please enter a number."); number1 = promptForDouble(prompt); } return number1; } private int promptForInt(String prompt) { int number2 = 0; print(prompt); String number = input(); try { number2 = Integer.parseInt(number); } catch(NumberFormatException e) { print("That is not an integer. Enter an integer."); number2 = promptForInt(prompt); } return number2; } public static void main(String[] args) { new Calculator(); } }
-
Data structure for iterating between players
I am new to programming, so I started working on a small guessing game for n players In theory they are supposed to take turns trying to guess some String, I've successfully implemented that game for 1 player, but now I am struggling with how to implement iterating over all players. My code right now looks something like this:
while (!gameIsFinished) { gameIsFinished = player1.takeTurn(); }
I guess I have to use some sort of Data structure to store all my players, but what would I choose in order to be able to iterate over them in a loop?
-
How do I shutil.move my file, post processing, in python based on filename?
My code-
import pandas as pd import datetime as dt import os import shutil path = "C:/Users/rocky/Desktop/autotranscribe/python/Matching" destination_path = ('C:/Users/rocky/Desktop/autotranscribe/python/Matching/Processed') for file in os.listdir("C:/Users/rocky/Desktop/autotranscribe/python/Matching"): if file.startswith("TVC")and "(updated headers)" not in file: dfs = pd.read_excel(file, sheet_name=None) output = dict() for ws, df in dfs.items(): if ws in ["Opt-Ins", "New Voting Members", "Temporary Members"]: continue if ws in ["Voting Members", "Removed Members"]: temp = df dt = pd.to_datetime(os.path.getctime(os.path.join(path,file)),unit="s").replace(nanosecond=0) temp['Status'] = "Active" if ws == "Voting Members" else "Cancelled" output[ws] = temp writer = pd.ExcelWriter(f'{file.replace(".xlsx","")} (updated headers).xlsx') for ws, df in output.items(): df.to_excel(writer, index=None, sheet_name=ws) writer.save() writer.close() shutil.move(path, destination_path )
I just want the file that is being processed here
if file.startswith("TVC")and "(updated headers)" not in file:
to be moved to another folder directory after all my code is processed and the output file is produced..where do i apply shutil.move? i put it outside my inner loop but the file didnt populate in my dest folder as expected. Do i need an if statement? if script runs successfully and output xls produced then move original file to destination folder?