Exploring the lesser-known side of JavaScript's Array.from() method
As a JavaScript developer, you've probably used Array.from() method to create a new array from an iterable or array-like object. But did you know that this method can do a lot more than just create an array?
🤔One lesser-known feature of Array.from() is that it can be used to transform and filter data during the array creation process. You can pass in a second argument, which is a map function that will be applied to each element of the iterable before it's added to the new array.
👉For example, let's say you have an array of numbers, and you want to create a new array that only contains the even numbers:
const numbers = [1, 2, 3, 4, 5, 6];
const evenNumbers = Array.from(numbers, num => num % 2 === 0 ? num : null);
Output:
[null, 2, null, 4, null, 6]
In this example, we pass in a map function that checks whether each number is even, and if it is, returns the number. If it's odd, it returns null. The result is a new array that only contains the even numbers.
💡Another lesser-known feature of Array.from() is that it can be used to create an array of a specific length, with each element initialized to a specific value. You can pass in an argument, which is the length of the array you want to create, and another argument, which is the initial value for each element.
Recommended by LinkedIn
👉For example, let's say you want to create an array of 10 elements, each initialized to the value 0:
const zeros = Array.from({ length: 10 }, () => 0);
Output:
[0, 0, 0, 0, 0, 0, 0, 0, 0, 0]
In this example, we create an object with a "length" property of 10, and pass it as the first argument to Array.from(). We also pass in a map function that returns the value 0 for each element. The result is a new array with 10 elements, each initialized to the value 0.
👨 💻 As a JavaScript developer, it's important to know about these lesser-known features of the language in order to write more robust and error-free code, and create new arrays in ways that you might not have thought possible before. Give them a try, and see what other creative ways you can come up with to use Array.from() in your JavaScript code.
🔎 What are some other hidden gems in JavaScript that you've discovered? Let me know in the comments below!
great concept
Thanks Aayush Patniya
excellent information