Thursday, 28 November 2024

Different Ways to Convert a Single Item to an Array in JavaScript

In JavaScript, there are various methods to wrap a single item in an array, each with unique advantages. Whether you're handling numbers, strings, or objects, this post will guide you through multiple ways to achieve the same goal.

From the simplest approach ([item]) to more flexible options like Array.of() and concat(), you'll learn how each method works and when each might be useful in your code.

 

Approach 1: Simply using [item]

const item = 5;
const array1 = [item];

 

Approach 2: Using Array.of()

The Array.of() method creates a new array with a variable number of arguments, regardless of number or type of the arguments.

const array2 = Array.of(item);

 

Approach 3: Using concat()

You can also use concat() to merge an item with an empty array, making it a single-item array.

 

const array3 = [].concat(item);

Approach 4: Using push() on an Empty Array

By initializing an empty array and pushing the item into it, you can achieve a similar result.

const array4 = [];
array4.push(item);

itemToArray.js

const item = 5;
const array1 = [item];

const array2 = Array.of(item);

const array3 = [].concat(item);

const array4 = [];
array4.push(item);

console.log(`item : ${item}`);
console.log(`array1 : ${array1}`);
console.log(`array2 : ${array2}`);
console.log(`array3 : ${array3}`);
console.log(`array4 : ${array4}`);

Output

item : 5
array1 : 5
array2 : 5
array3 : 5
array4 : 5

 

Previous                                                    Next                                                    Home

No comments:

Post a Comment