How can I convert an array-like object to an array in JavaScript?
Gable E
gable e profile pic

In JavaScript, you can convert an array-like object to an actual array using various techniques. Array-like objects are objects that have a length property and indexed elements but do not inherit from theArray prototype. Here are a few methods to convert an array-like object to an array: 1. Array.from(): - TheArray.from() method creates a new array from an iterable object or array-like object. - It takes the object as the first argument and returns a new array with the same elements.

1
2
3
4

   const arrayLike = { 0: 'apple', 1: 'banana', 2: 'orange', length: 3 };
   const array = Array.from(arrayLike);
   

In this example,Array.from(arrayLike) creates a new array from thearrayLike object, which has indexed elements and a length property. The resultingarray will be['apple', 'banana', 'orange']. 2. Spread Operator: - The spread operator (...) can be used to spread elements of an iterable or array-like object into a new array.

1
2
3
4

   const arrayLike = { 0: 'apple', 1: 'banana', 2: 'orange', length: 3 };
   const array = [...arrayLike];
   

Using the spread operator[...arrayLike] spreads the elements of thearrayLike object into a new array. It achieves the same result asArray.from(). 3. Array.prototype.slice.call(): - TheArray.prototype.slice.call() method is an older approach that converts an array-like object to an array by using theslice() method in the context of theArray prototype.

1
2
3
4

   const arrayLike = { 0: 'apple', 1: 'banana', 2: 'orange', length: 3 };
   const array = Array.prototype.slice.call(arrayLike);
   

Here,Array.prototype.slice.call(arrayLike) creates a new array by calling theslice() method with thearrayLike object as the context. 4. Array.prototype.concat(): - TheArray.prototype.concat() method can be used to concatenate the elements of an array-like object with an existing array, effectively creating a new array.

1
2
3
4

   const arrayLike = { 0: 'apple', 1: 'banana', 2: 'orange', length: 3 };
   const array = [].concat(arrayLike);
   

In this example,[].concat(arrayLike) concatenates the elements ofarrayLike with an empty array, resulting in a new array. All of these methods effectively convert an array-like object to a proper array. Choose the method that best suits your needs and JavaScript version compatibility. It's important to note that these methods create a new array rather than modifying the original array-like object.