Rubypic

Ruby Jane Cabagnot

Using Array.from() for Array Manipulation : A Guide and Lessons Learned

JavaScript’s Array.from() method is a powerful utility that enables you to convert an array-like object or a collection into a real JavaScript array. It provides a concise way to create new arrays from iterable objects, making it easier to manipulate and work with arrays in JavaScript. In this blog, we’ll explore how to use Array.from() for array manipulation and share some lessons learned from the experience.

Getting Started

To begin, ensure you have a text editor or an IDE installed. If not, you can install one such as Visual Studio Code from the official website.

Next, open your terminal or command prompt and create a new directory for your project:


function createPagination(totalPages, currentPage) {
    const visiblePages = 5;
    const halfVisible = Math.floor(visiblePages / 2);
    const firstVisiblePage = Math.max(1, currentPage - halfVisible);
    const lastVisiblePage = Math.min(totalPages, firstVisiblePage + visiblePages - 1);

    const pages = Array.from({ length: lastVisiblePage - firstVisiblePage + 1 }, (_, index) => index + firstVisiblePage);

    return pages;
}

const totalPages = 10;
const currentPage = 5;

const pagination = createPagination(totalPages, currentPage);

console.log(pagination);

In this example, we have a function createPagination that generates an array of visible page numbers based on the total number of pages and the current page. We use Array.from() to create an array of page numbers from the first visible page to the last visible page. The length parameter specifies the number of elements in the array, and the callback function generates the page numbers based on the index and the first visible page.


// Create an array of numbers from 0 to 9 using Array.from() with a callback function.The _, index parameters represent the current element and its index, respectively. I am concerned with the index because I want to generate an array of numbers from 0 to 9.

const items = Array.from({length: 120}, {_, index} => {
    return index
})

console.log(items)
const itemsPerPage = 14;
// Calculate the total number of pages based on the number of items and items per page. The Math.ceil() function rounds up to the nearest whole number.
const pages = Math.ceil(items.length / itemsPerPage); 

const newItems = Array.from({length: pages}, (_, index) => {
    // We multiply the index by itemsPerPage because we want to calculate the starting index of the slice method.
    // The slice method takes two arguments: the starting index and the ending index.
    // The starting index is the index of the first item we want to include in the slice.
    // The ending index is the index of the last item we want to include in the slice.
    // By multiplying the index by itemsPerPage, we are effectively calculating the starting index of the slice.
    // For example, if the index is 0 and itemsPerPage is 14, the starting index would be 0.
    // If the index is 1, the starting index would be 14 (0 + 14).
    // If the index is 2, the starting index would be 28 (14 + 14).
    // And so on.
    // By using this calculation, we ensure that we are always slicing the correct number of items from the original array.
    // This is important because the slice method does not modify the original array.
    // Instead, it returns a new array that contains the specified range of elements from the original array.
    const start = index * itemsPerPage;
    const end = start + itemsPerPage;
    // The slice() method returns a shallow copy of a portion of an array into a new array object selected from start to end (end not included).
    // The syntax is slice(start, end).
    // The start parameter is the index at which to begin extraction.
    // The end parameter is optional. If omitted, slice() extracts through the end of the array.
    // The slice() method does not modify the original array. Instead, it returns a new array.
    // In our case, we use slice() to extract a portion of the items array based on the start and end indices.
    // The start and end indices are calculated based on the index of the current page and itemsPerPage.
    // This way, we are extracting the correct range of items from the original items array for each page.
    return items.slice(start, end);
});

console.log(newItems);

Lessons Learned

  1. Creating Arrays with a Specified Length: Array.from() allows you to create arrays with a specified length by passing an object with a length property. This is useful when you need to generate arrays of a specific size without initializing the elements. For example, if you want to create an array of 5 empty strings, you can use Array.from() like this:

    const emptyStrings = Array.from({length: 5}, () => ”); console.log(emptyStrings); // Output: ["", "", "", "", ""]

    In this example, the callback function passed to Array.from() is a constant function that returns an empty string. This creates an array of 5 empty strings without having to explicitly initialize each element.

  2. Generating Array Elements with a Callback Function: The second argument of Array.from() is a callback function that generates array elements dynamically. The callback function receives two arguments: the current element and its index. This allows you to create arrays with custom values or patterns.

Here’s an example that demonstrates how to use the callback function to generate an array of squares of numbers:

const numbers = [1, 2, 3, 4, 5];
const squares = Array.from(numbers, (num) => num * num);
console.log(squares); // Output: [1, 4, 9, 16, 25]

In this example, the callback function multiplies each number in the `numbers` array by itself to generate an array of squares. This demonstrates how you can use the callback function to transform array elements based on custom logic.

3. Converting Array-Like Objects to Arrays: You can convert array-like objects or iterable objects into real arrays using Array.from(). This is helpful when working with DOM elements, strings, or other iterable objects that are not true arrays. Here’s an example:

const nodeList = document.querySelectorAll('li');
const array = Array.from(nodeList);
console.log(array); // Output: [<li>...</li>, <li>...</li>, ...]

In this example, the Array.from() function is used to convert the NodeList returned by the querySelectorAll() method into a real array. Now you can work with the array like any other array and take advantage of all the array methods available in JavaScript.

4. Creating Arrays from Collections: You can use Array.from() to create arrays from collections such as Set, Map, or NodeList. This simplifies the process of converting collections into arrays for easier manipulation and iteration.

Here’s an example that demonstrates how to create an array from a Set:

const set = new Set([1, 2, 3, 4, 5]);
const array = Array.from(set);
console.log(array); // Output: [1, 2, 3, 4, 5]

In this example, the Array.from() method is used to convert a Set into an array. This allows you to work with the set elements as an array and perform array operations on them.

5. Using Array.from() with Spread Operator: You can combine Array.from() with the spread operator (…) to convert iterable objects into arrays. This is a concise way to create arrays from iterable objects without using the Array.from() method explicitly.

Here’s an example that demonstrates how to use the spread operator with Array.from():

const iterable = 'hello
const array = [...iterable];
console.log(array); // Output: ['h', 'e', 'l', 'l', 'o']

In this example, the spread operator is used to convert the iterable string into an array. This is a shorthand way to achieve the same result as using Array.from() with the iterable object.

By leveraging the power of Array.from(), you can simplify array manipulation tasks and work more efficiently with arrays in JavaScript.

Whether you need to create arrays with specific lengths, generate array elements dynamically, or convert array-like objects to real arrays, Array.from() provides a versatile and convenient solution for array manipulation.

Try using Array.from() in your next JavaScript project and explore its capabilities for working with arrays effectively.

Conclusion

In this blog, we’ve explored how to use Array.from() for array manipulation in JavaScript and shared some valuable lessons learned from the experience. Array.from() is a versatile method that simplifies array creation, manipulation, and conversion tasks, making it easier to work with arrays in JavaScript.

By understanding the capabilities of Array.from() and its various use cases, you can enhance your array manipulation skills and write cleaner, more efficient code. Experiment with Array.from() in your projects and discover the benefits of using this powerful utility for array manipulation in JavaScript. Happy coding!