Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript Array Concat not working. Why?

People also ask

Why concat is not working in JS?

To solve the error, console. log the value you're calling the concat method on and make sure it's a valid array. Copied! const arr1 = [{name: 'Tom'}]; const arr2 = [{name: 'James'}]; const arr3 = arr1.

How do you concatenate an array in JavaScript?

concat() The concat() method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Can we concat two arrays in JavaScript?

The concat() method concatenates (joins) two or more arrays. The concat() method returns a new array, containing the joined arrays. The concat() method does not change the existing arrays.

How does concat work in JavaScript?

Description. In JavaScript, concat() is a string method that is used to concatenate strings together. The concat() method appends one or more string values to the calling string and then returns the concatenated result as a new string.


The concat method doesn't change the original array, you need to reassign it.

if ( ref instanceof Array )
   this.refs = this.refs.concat( ref );
else
   this.refs.push( ref );

Here is the reason why:

Definition and Usage

The concat() method is used to join two or more arrays.

This method does not change the existing arrays, but returns a new array, containing the values of the joined arrays.

You need to assign the result of the concatenation back in the array that you have.


To expand on Konstantin Dinev:

.concat() doesn't add to current object, so this will not work:

foo.bar.concat(otherArray);

This will:

foo.bar = foo.bar.concat(otherArray);

you have to re-assign value using = to array , that you want to get concated value

let array1=[1,2,3,4];
let array2=[5,6,7,8];

array1.concat(array2);
console.log('NOT WORK :  array1.concat(array2); =>',array1);

array1= array1.concat(array2);
console.log('WORKING :  array1 = array1.concat(array2); =>',array1);