Push an array into the same array JS
Topics related to client-side programming language.
Post questions and answers about JavaScript, Ajax, or jQuery codes and scripts.
-
Marius
- Posts: 106
Push an array into the same array JS
I'm trying to push an array into the same array in javascript, But it doesn't seem to be working; the third element is added continuously.
Here is my code so far:
Code: Select all
var arr = ['Hello', 'World!']
arr.push(arr);
console.log(arr);
Expected output: ['Hello', 'World!', ['Hello', 'World!']]
Does somebody know why my code doesn't work, and how to fix it?
Admin
You are trying to push the same reference to the array. So, when the array updated later, the array inside the element will be updated as well.
To fix this, you need to push a copy of the array (another reference).
See the sample below.
Code: Select all
var arr = ['Hello', 'World!']
arr.push([...arr]);
console.log(arr);
Similar Topics
-
Check if multidimensional array
PHP - MySQL
First post
How can I check in php if an array is multidimensional or not?
I get a JSON from a third-party application and I parse it in php. But sometimes data...
Last post
You can check with two count() functions. If you add a second argument as True it will recursively count the array.
Here is an example:
$arr =[...
-
Get array with ID and Users from database
PHP - MySQL
First post
Without real knowledge the gambling remains & questions arise
& without the support from Coursesweb it is checkmate for me :D
I found a...
Last post
I found the answer:
// SELECT sql query
$sql = SELECT * FROM `user` ORDER BY `id` DESC ;
// perform the query and store the result
$result =...
-
Check for an array of words in a string in php
PHP - MySQL
First post
I have a list of spam words that are into an array. When a user submits a string text, I want to know if it contains these words. How can I do this...
Last post
You could add the spam words into a string, with | as word separator and then use regular expression to check.
$my_words =...
-
Find item in array and set as first index
JavaScript - jQuery - Ajax
First post
Say I have the following array of persons:
const arr =
And I want to find a certain person (name) in this array, and put it as the first...
Last post
You could sort the array with the sort() method.
This approach moves all objects with the wanted 'name' to top.
const arr = ;
let first =...
-
Split an array of objects into separate arrays
JavaScript - jQuery - Ajax
First post
I have an array of objects, and for plotting a graph I need to split it into 3 different arrays. How to do it using JS?
const dataOverview = ;
I...
Last post
It is very simple, you just use the map() function.
var series1 = dataOverview.map(x => x.series1);
var series2 = dataOverview.map(x =>...