Javascript array join two arrays

Array.prototype.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.

Try it

Syntax

concat() concat(value0) concat(value0, value1) concat(value0, value1, /* … ,*/ valueN) 

Parameters

Arrays and/or values to concatenate into a new array. If all valueN parameters are omitted, concat returns a shallow copy of the existing array on which it is called. See the description below for more details.

Return value

Description

The concat method creates a new array. The array will first be populated by the elements in the object on which it is called. Then, for each argument, its value will be concatenated into the array — for normal objects or primitives, the argument itself will become an element of the final array; for arrays or array-like objects with the property Symbol.isConcatSpreadable set to a truthy value, each element of the argument will be independently added to the final array. The concat method does not recurse into nested array arguments.

Читайте также:  Контрольная сумма снилс python

The concat() method is a copying method. It does not alter this or any of the arrays provided as arguments but instead returns a shallow copy that contains the same elements as the ones from the original arrays.

The concat() method preserves empty slots if any of the source arrays is sparse.

The concat() method is generic. The this value is treated in the same way as the other arguments (except it will be converted to an object first), which means plain objects will be directly prepended to the resulting array, while array-like objects with truthy @@isConcatSpreadable will be spread into the resulting array.

Examples

Concatenating two arrays

The following code concatenates two arrays:

const letters = ["a", "b", "c"]; const numbers = [1, 2, 3]; const alphaNumeric = letters.concat(numbers); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3] 

Concatenating three arrays

The following code concatenates three arrays:

const num1 = [1, 2, 3]; const num2 = [4, 5, 6]; const num3 = [7, 8, 9]; const numbers = num1.concat(num2, num3); console.log(numbers); // results in [1, 2, 3, 4, 5, 6, 7, 8, 9] 

Concatenating values to an array

The following code concatenates three values to an array:

const letters = ["a", "b", "c"]; const alphaNumeric = letters.concat(1, [2, 3]); console.log(alphaNumeric); // results in ['a', 'b', 'c', 1, 2, 3] 

Concatenating nested arrays

The following code concatenates nested arrays and demonstrates retention of references:

const num1 = [[1]]; const num2 = [2, [3]]; const numbers = num1.concat(num2); console.log(numbers); // results in [[1], 2, [3]] // modify the first element of num1 num1[0].push(4); console.log(numbers); // results in [[1, 4], 2, [3]] 

Concatenating array-like objects with Symbol.isConcatSpreadable

concat does not treat all array-like objects as arrays by default — only if Symbol.isConcatSpreadable is set to a truthy value (e.g. true ).

const obj1 =  0: 1, 1: 2, 2: 3, length: 3 >; const obj2 =  0: 1, 1: 2, 2: 3, length: 3, [Symbol.isConcatSpreadable]: true >; console.log([0].concat(obj1, obj2)); // [ 0, < '0': 1, '1': 2, '2': 3, length: 3 >, 1, 2, 3 ] 

Using concat() on sparse arrays

If any of the source arrays is sparse, the resulting array will also be sparse:

.log([1, , 3].concat([4, 5])); // [1, empty, 3, 4, 5] console.log([1, 2].concat([3, , 5])); // [1, 2, 3, empty, 5] 

Calling concat() on non-array objects

If the this value is not an array, it is converted to an object and then treated in the same way as the arguments for concat() . In this case the return value is always a plain new array.

.log(Array.prototype.concat.call(>, 1, 2, 3)); // [<>, 1, 2, 3] console.log(Array.prototype.concat.call(1, 2, 3)); // [ [Number: 1], 2, 3 ] const arrayLike =  [Symbol.isConcatSpreadable]: true, length: 2, 0: 1, 1: 2, 2: 99, // ignored by concat() since length is 2 >; console.log(Array.prototype.concat.call(arrayLike, 3, 4)); // [1, 2, 3, 4] 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

Array.prototype.join()

The join() method creates and returns a new string by concatenating all of the elements in an array (or an array-like object), separated by commas or a specified separator string. If the array has only one item, then that item will be returned without using the separator.

Try it

Syntax

Parameters

Specifies a string to separate each pair of adjacent elements of the array. The separator is converted to a string if necessary. If omitted, the array elements are separated with a comma («,»). If separator is an empty string, all elements are joined without any characters in between them.

Return value

A string with all array elements joined. If arr.length is 0 , the empty string is returned.

Description

The string conversions of all array elements are joined into one string. If an element is undefined , null , it is converted to an empty string instead of the string «null» or «undefined» .

The join method is accessed internally by Array.prototype.toString() with no arguments. Overriding join of an array instance will override its toString behavior as well.

Array.prototype.join recursively converts each element, including other arrays, to strings. Because the string returned by Array.prototype.toString (which is the same as calling join() ) does not have delimiters, nested arrays look like they are flattened. You can only control the separator of the first level, while deeper levels always use the default comma.

const matrix = [ [1, 2, 3], [4, 5, 6], [7, 8, 9], ]; console.log(matrix.join()); // 1,2,3,4,5,6,7,8,9 console.log(matrix.join(";")); // 1,2,3;4,5,6;7,8,9 

When an array is cyclic (it contains an element that is itself), browsers avoid infinite recursion by ignoring the cyclic reference.

const arr = []; arr.push(1, [3, arr, 4], 2); console.log(arr.join(";")); // 1;3,,4;2 

When used on sparse arrays, the join() method iterates empty slots as if they have the value undefined .

The join() method is generic. It only expects the this value to have a length property and integer-keyed properties.

Examples

Joining an array four different ways

The following example creates an array, a , with three elements, then joins the array four times: using the default separator, then a comma and a space, then a plus and an empty string.

const a = ["Wind", "Water", "Fire"]; a.join(); // 'Wind,Water,Fire' a.join(", "); // 'Wind, Water, Fire' a.join(" + "); // 'Wind + Water + Fire' a.join(""); // 'WindWaterFire' 

Using join() on sparse arrays

join() treats empty slots the same as undefined and produces an extra separator:

.log([1, , 3].join()); // '1,,3' console.log([1, undefined, 3].join()); // '1,,3' 

Calling join() on non-array objects

The join() method reads the length property of this and then accesses each property whose key is a nonnegative integer less than length .

const arrayLike =  length: 3, 0: 2, 1: 3, 2: 4, 3: 5, // ignored by join() since length is 3 >; console.log(Array.prototype.join.call(arrayLike)); // 2,3,4 console.log(Array.prototype.join.call(arrayLike, ".")); // 2.3.4 

Specifications

Browser compatibility

BCD tables only load in the browser

See also

Found a content problem with this page?

This page was last modified on Jun 27, 2023 by MDN contributors.

Your blueprint for a better internet.

Источник

How to join two arrays in JavaScript

There are a few ways how you can join two arrays in JavaScript, a spread syntax, a concat() method, and a push() method.

Often joining two arrays is called array merging.

Given you have two arrays:

const fruits = ['banana', 'apple'] const veggies = ['corn', 'pumpkin'] 

Joining arrays with the Spread syntax

The spread syntax (or spread operator) is used when items from and iterable need to be expanded, e.g. in the array.

So to join fruits and veggies arrays, we’ll create a new variable and assign it a new array:

const foods = [. fruits, . veggies] foods // ['banana', 'apple', 'corn', 'pumpkin'] 

Using this approach you can actually join multiple arrays:

const foods = [. fruits, . veggies, . dairy, . grains] 

Browser support for the Spread syntax: supported in all major browsers except IE.

Joining arrays with the .concat() method

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

You can use it the similar way as the above example, create a new variable and assign it a merged array:

const foods = fruits.concat(veggies) foods // ['banana', 'apple', 'corn', 'pumpkin'] 

NOTE: The concat() method does not change the existing arrays but instead returns a new array.

To join multiple arrays, just specify each array as an additional argument to the concat() method:

// another way to use the concat method const foods = [].concat(fruits, veggies, dairy, grains) 

Browser support for the concat() method: supported in all major browsers.

Joining arrays with the .push() method

In case you want to join arrays and update the value of the initial array (mutate it) you can use the push() method.

The push() method adds one or more elements to the end of an array. In order to push a whole array, you’ll need to use the Spread syntax:

fruits.push(. veggies) fruits // ['banana', 'apple', 'corn', 'pumpkin'] 

The push() methods accept multiple arguments, so you can join multiple arrays into one:

fruits.push(. veggies, . dairy, . grains) 

The push() method is a useful approach inside the loops when you need to update the existing array.

Browser support for the push() method: supported in all major browsers.

Dealing with duplicates

In case the array items you’re joining are strings or numbers, there might be a case when you need to merge duplicate values. So that each item is unique and appears once in the array.

To deal with duplicates you can use the Set object and assign it to a new variable:

const fruits = ['banana', 'apple', 'tomato'] const veggies = ['corn', 'pumpkin', 'tomato'] const foods = [. new Set([. fruits, . veggies])] foods // ['banana', 'apple', 'tomato', 'corn', 'pumpkin'] 

In case you’re joining arrays that hold objects or mixed type value items I recommend using the lodash library to check for duplicates and merge them.

Example from lodash using the unionWith method to join two arrays that has a duplicate item:

var objects = [ 'x': 1, 'y': 2 >,  'x': 2, 'y': 1 >] var others = [ 'x': 1, 'y': 1 >,  'x': 1, 'y': 2 >] _.unionWith(objects, others, _.isEqual) // => [< 'x': 1, 'y': 2 >, < 'x': 2, 'y': 1 >, < 'x': 1, 'y': 1 >] 

Источник

JavaScript Array concat()

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.

See Also:

Syntax

Parameters

Return Value

More Examples

Concatenate strings and numbers:

Concatenate nested arrays:

Browser Support

concat() is an ECMAScript1 (ES1) feature.

ES1 (JavaScript 1997) is fully supported in all browsers:

Chrome Edge Firefox Safari Opera IE
Yes Yes Yes Yes Yes Yes

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

Оцените статью