×

Index

JavaScript Tutorial

JavaScript Examples

CSS Tutorial

CSS Examples

JavaScript - Using concat() on sparse arrays

By IncludeHelp Last updated : January 20, 2024

In JavaScript, a sparse array is an array in which the elements do not have contiguous indexes starting at 0.

Problem statement

Given two Sparse arrays, we have to add them and check what will be the result of the concatenated array.

Concatenating sparse arrays

To concatenate two sparse arrays, use Array.concat() method, the concat() method also returns a sparse array if the inputs are sparse arrays.

JavaScript code to concatenate two sparse arrays

The following example concatenates two sparse arrays arr1 and arr2.

// creating two sparse arrays
const arr1 = [1, , 3];
const arr2 = [4, , 5, 6, , 7];

// concatenating sparse arrays
const result = arr1.concat(arr2);

// printing arrays
console.log("arr1:", arr1);
console.log("arr2:", arr2);
console.log("result:", result);

Output

The output of the above code is:

arr1: [1, empty, 3]
arr2: [4, empty, 5, 6, empty, 7]
result: [1, empty, 3, 4, empty, 5, 6, empty, 7]

To understand the above example, you should have the basic knowledge of the following JavaScript topics:

Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.